package com.dminvoicemanager;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import com.dminvoicemanager.backup.DM_Excel_Generator;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class DM_Application_Manage_Tools extends Activity {

	private static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanager.db";
	private SQLiteDatabase mydb;
	// Master Tables
	private String SERVER_DB_LIST = "serverdb";
	private String USER_SETTINGS = "usersettings";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String INV_SAL_REP = "fSalRep";
	private String SALES_ORD_REASON = "fReason";
	private String SALES_REP_ROUTE = "fRoute";
	private String SALES_REP_ROUTEDET = "fRouteDet";
	private String BANK_DETAILS = "fBank";
	private String USER_EXPENSE = "fExpense";
	private String TOWN_DETAILS = "fTown";
	private String MERCH_DETAILS = "FMerch";
	private String YEARS_LIST = "FYearsList";
	private String MONTH_LIST = "FMonthList";
	private String SERVER_DETAILS = "serverinfo";
	private String SALES_DEALER = "fDealer";
	private String FTRGCAPUL = "FTrgCapUL";
	private String FTYPE = "fType";
	private String FSUBBRAND = "fSubBrand";
	private String FGROUP = "fGroup";
	private String FSKU = "fSku";
	private String FBRAND = "fbrand";

	// Main Invoice
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";
	// Sales Orders
	private String STOCK_ORDER_HEAD = "FOrdHed";
	private String STOCK_ORDER_DETAIL = "FOrddet";
	// Stock UnLoading
	private String TEMP_STOCK_LOADING_SUMMARYUN = "frepStockLoadingSummaryUn";
	private String STOCK_LOAD_HEADUN = "fUnLoadhed";
	private String STOCK_LOAD_DETAILUN = "fUnLoadDet";
	// Cash /Receipt header
	private String TEMP_RECEIPT_SUMMARY = "fReceiptSummary";
	private String RECEIPT_HEADER = "fDRecHed";
	private String RECEIPT_DETAILS = "fDRecDet";
	// Stock Damage
	private String TEMP_STOCK_LOADING_SUMMARYDAM = "frepStockLoadingSummaryDam";
	private String STOCK_LOAD_HEADDAM = "fDamhed";
	private String STOCK_LOAD_DETAILDAM = "fDamdet";
	// Adjustment
	private String TEMP_ADJUSTMENT_SUMMARY = "FAdjustmentSummary";
	private String ADJUST_ADDITION_HEADER = "FAdjHed";
	private String ADJUST_ADDITION_DETAILS = "FAdjDet";

	String connectionURL, serverDBName, currentUserServerDB;
	String UploadodAddDate;
	String AgentPrefixType, AgentDealCode;
	TextView manageToolsHed;
	Button dropTables, downloadData, generatePDF, uploadDatabutton,
			excelgenerator;
	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
	Date date;
	int checkrall = 0;
	String currentUserTemp, currentUserPrefix, UserLocCode, serverDbName,
			RepRouteCode;
	ArrayList<String> arFinvHed = new ArrayList<String>();
	ArrayList<String> arFinvDet = new ArrayList<String>();

	ArrayList<String> arFordHed = new ArrayList<String>();
	ArrayList<String> arFordDet = new ArrayList<String>();

	ArrayList<String> arCanceleInvHedDet = new ArrayList<String>();
	ArrayList<String> arCanceleOrdHedDet = new ArrayList<String>();

	ArrayList<String> arfUnLoadhed = new ArrayList<String>();
	ArrayList<String> arfUnLoadDet = new ArrayList<String>();

	ArrayList<String> arfDRecHed = new ArrayList<String>();
	ArrayList<String> arfDRecDet = new ArrayList<String>();

	ArrayList<String> arfDamHed = new ArrayList<String>();
	ArrayList<String> arfDamDet = new ArrayList<String>();

	ArrayList<String> arFAdjHed = new ArrayList<String>();
	ArrayList<String> arFAdjDet = new ArrayList<String>();

	InputStream is = null;
	InputStream isp = null;
	StringBuilder sb = null;
	StringBuilder sbp = null;
	Cursor selectInvHeadDetailsReChk = null, selectInvDetailsDataReChk = null;
	int fInvHedCount = 0;
	int fOrdHedCount = 0;
	int fInvHedCountFail = 0;
	int fOrdHedCountFail = 0;
	int arrayLength = 0;
	String SIupSummary, SOupSummary, ReadRefErrorUpload;
	Cursor selectInvHeadDetailsUpdate = null,
			selectInvDetailsDataUpdate = null;
	Cursor selectInvHeadDetailsChkFail = null,
			selectInvDetailsDataChkFail = null;
	AlertDialog SynchDetails = null;
	
	public void btnExitSettings(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_InvoiceMainActivity.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_application_manage_tools);
		currentuserTemp();
		checkCurrentServerDB();
		manageToolsHed = (TextView) findViewById(R.id.txtHeading);
		manageToolsHed.setText("Manage Tools");
		getConnectionUrl();
		getServerDBName();
		agentPrefixSalesOrder();
		dropTables = (Button) findViewById(R.id.dropTables);
		dropTables.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				dropCurrentTables();
				createMasterTables();
			}

		});

		downloadData = (Button) findViewById(R.id.downloadData);
		downloadData.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

			}
		});

		generatePDF = (Button) findViewById(R.id.pdfgenerator);
		generatePDF.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_PDF_Viewer.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});

		excelgenerator = (Button) findViewById(R.id.excelgenerator);
		excelgenerator.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_Excel_Generator.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});

		uploadDatabutton = (Button) findViewById(R.id.uploadDatabutton);
		uploadDatabutton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				uploadingInvoiceData();
			}
		});

		Button uploadDatabuttonTesting = (Button) findViewById(R.id.uploadingDataTesting);
		uploadDatabuttonTesting.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				uploadingInvoiceDataTesting();
			}
		});

	}

	protected void uploadingInvoiceDataTesting() {
		// TODO Auto-generated method stub
		new UploadingInvoiceDataValuesTesting().execute();
	}

	// ====================================================================
	protected void uploadingInvoiceData() {
		// TODO Auto-generated method stub
		new UploadingInvoiceDataValues().execute();
	}

	private class UploadingInvoiceDataValues extends
			AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					DM_Application_Manage_Tools.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Invoice Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			Cursor selectFcompanyBranch = null; 
			// Secondry Invoice Cursors
			Cursor selectInvHeadDetails = null;
			Cursor selectInvDetailsData = null;
			// Sales Order Invoice Cursors
			Cursor selectOrderHeader = null;
			Cursor selectOrderDetails = null;
			// Secondry invoice Cancel Details
			Cursor selectSIcancelHedDetDetails = null;
			Cursor selectSOcancelHedDetDetails = null;

			// Unloading Records Details
			Cursor selectStockUnloadHeader = null;
			Cursor selectStockUnLoadDetails = null;

			// Receipt Records Details
			Cursor selectReceiptHeadDetails = null;
			Cursor selectInvReceiptDetails = null;

			// Damage Records Details
			Cursor selectStockfDamhed = null;
			Cursor selectStockfDamDet = null;

			// Adjustment Records Details
			Cursor selectAdjustmentHeader = null;
			Cursor selectAdjustmentDetails = null;

			// *******Secondry Invoice********

			try {
				selectInvHeadDetails = mydb.query(INV_HEADER, null,
						"invhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			try {
				selectInvDetailsData = mydb.query(INV_DETAILS, null,
						"invdetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			// *******Sales Orders Invoice********
			try {
				selectOrderHeader = mydb.query(STOCK_ORDER_HEAD, null,
						"stordhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			try {
				selectOrderDetails = mydb.query(STOCK_ORDER_DETAIL, null,
						"storddetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// Canceled Secondry Invoice Uploading
			try {
				String queryCancelSI = "SELECT FH.RefNo,FH.RefNo1,FH.InvType,FH.TxnDate,FH.ManuRef,FH.DealCode,FH.RepCode,FH.AreaCode,FH.RouteCode,FH.DebCode,FH.LocCode,FH.Remarks,FH.CostCode,FH.CurCode,FH.CurRate,FH.TxnType,FH.InvAmt,FH.OutDis,FH.InvDis,FH.TotMkrAmt,FH.UnOvAmt,FH.TotalDis,FH.TotalAmt,FH.AddUser,FH.AddDateInvHead,FH.AddMach,FH.prtcopy,FD.RefNo,FD.SeqNo,FD.Itemcode,FD.Txnseqno,FD.SellPrice,FD.BSellPrice,FD.TSellPrice,FD.BTSellPrice,FD.CostPrice,FD.CaseQty,FD.PiceQty,FD.Type,FD.Qty,FD.BalQty,FD.DisPer,FD.DisAmt,FD.BDisAmt,FD.itemdisper,FD.itemdisperval,FD.TaxAmt,FD.BTaxAmt,FD.Amt,FD.Bamt,FD.ReaCode,FD.Linkrec,FSUM.invoiceComplete,FSUM.invoiceRef FROM Finvhed FH,FinvDet FD,frepInvoiceSumery FSUM Where FH.RefNo = FD.RefNo AND FH.RefNo = FSUM.invoiceRef AND FSUM.invoiceComplete = '5'";
				selectSIcancelHedDetDetails = mydb
						.rawQuery(queryCancelSI, null);
			} catch (Exception e) {
			}
			// Canceled Sales Order Invoice Uploading
			try {
				String queryCancelSO = "SELECT OH.RefNo,OH.TxnDate,OH.ManuRef,OH.DelvDate,OH.DealCode,OH.RepCode,OH.AreaCode,OH.RouteCode,OH.DebCode,OH.LocCode,OH.Remarks,OH.CostCode,OH.CurCode,OH.CurRate,OH.TxnType,OH.InvAmt,OH.OutDis,OH.InvDis,OH.TotMkrAmt,OH.UnOvAmt,OH.TotalDis,OH.TotalAmt,OH.InvFlg,OD.SeqNo,OD.Itemcode,OD.Txnseqno,OD.SellPrice,OD.BSellPrice,OD.TSellPrice,OD.BTSellPrice,OD.CostPrice,OD.CaseQty,OD.PiceQty,OD.Type,OD.Qty,OD.BalQty,OD.DisPer,OD.DisAmt,OD.BDisAmt,OD.TaxAmt,OD.BTaxAmt,OD.Amt,OD.Bamt,OD.ReaCode,OH.AddUser,OH.ohAddDate,OH.AddMach,OH.prtcopy,OD.itemdisper,OD.itemdisperval,OSUM.invoiceComplete,OSUM.invoiceRef,OD.RefNo,OH.AddMach FROM FOrdHed OH,FOrddet OD,fstockordInvoiceSumery OSUM Where OH.RefNo = OD.RefNo AND OH.RefNo = OSUM.invoiceRef AND OSUM.invoiceComplete = '5'";
				selectSOcancelHedDetDetails = mydb
						.rawQuery(queryCancelSO, null);
			} catch (Exception e) {
			}

			// Stocks Unloading Header Uploading
			// Unloading header
			try {
				selectStockUnloadHeader = mydb.query(STOCK_LOAD_HEADUN, null,
						"stlhedunSync = '0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectStockUnLoadDetails = mydb.query(STOCK_LOAD_DETAILUN,
						null, "stldetunSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// Receipt Uploading
			try {
				selectReceiptHeadDetails = mydb.query(RECEIPT_HEADER, null,
						"recipthedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			try {
				selectInvReceiptDetails = mydb.query(RECEIPT_DETAILS, null,
						"reciptdetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			// Damage Transfer
			try {
				selectStockfDamhed = mydb.query(STOCK_LOAD_HEADDAM, null,
						"stldmhedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectStockfDamDet = mydb.query(STOCK_LOAD_DETAILDAM, null,
						"stldmdetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			// Stock adjustment , deduction header
			try {
				selectAdjustmentHeader = mydb.query(ADJUST_ADDITION_HEADER,
						null, "adjHedSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}

			try {
				selectAdjustmentDetails = mydb.query(ADJUST_ADDITION_DETAILS,
						null, "adjDetSync ='0'", null, null, null, null);
			} catch (Exception e) {
			}
			// *******Secondry Invoice Uploading Start********
			// ******Upload FInvHed**************
			if (selectInvHeadDetails != null) {
				if (selectInvHeadDetails.getCount() > 0) {
					while (selectInvHeadDetails.moveToNext()) {
						String RefNo = selectInvHeadDetails.getString(1);
						String RefNo1 = selectInvHeadDetails.getString(2);
						String InvType = selectInvHeadDetails.getString(3);
						String TxnDate = selectInvHeadDetails.getString(4);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);
						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectInvHeadDetails.getString(5);
						String DealCode = selectInvHeadDetails.getString(6);
						String RepCode = selectInvHeadDetails.getString(7);
						String AreaCode = selectInvHeadDetails.getString(8);
						String RouteCode = selectInvHeadDetails.getString(9);
						String DebCode = selectInvHeadDetails.getString(10);
						String LocCode = selectInvHeadDetails.getString(11);
						String Remarks = selectInvHeadDetails.getString(12);
						String CostCode = selectInvHeadDetails.getString(13);
						String CurCode = selectInvHeadDetails.getString(14);
						String CurRate = selectInvHeadDetails.getString(15);
						String TxnType = selectInvHeadDetails.getString(16);
						String InvAmt = selectInvHeadDetails.getString(17);
						String OutDis = selectInvHeadDetails.getString(18);
						// Invoice Discount Value
						String InvDis = selectInvHeadDetails.getString(19);
						double InvDisVal = Double.parseDouble(InvDis
								.replaceAll("[,]", ""));
						String TotMkrAmt = selectInvHeadDetails.getString(20);
						String UnOvAmt = selectInvHeadDetails.getString(21);
						// Total Discount
						String TotalDis = selectInvHeadDetails.getString(22);
						double TotalDisVal = Double.parseDouble(TotalDis
								.replaceAll("[,]", ""));
						String TotalAmt = selectInvHeadDetails.getString(23);
						double TotalAmtdou = Double.parseDouble(TotalAmt
								.replaceAll("[,]", ""));
						double FTotalAmt = TotalAmtdou + 0.00;
						String PrintFTotalAmt = Double.toString(FTotalAmt);
						String AddUser = selectInvHeadDetails.getString(24);
						String AddDate = selectInvHeadDetails.getString(25);
						String AddMach = selectInvHeadDetails.getString(26);
						String prtcopy = selectInvHeadDetails.getString(27);
						String TranBatch = selectInvHeadDetails.getString(30);
						// Header Discount
						String outDisVal = selectInvHeadDetails.getString(33);
						double outDisValue = Double.parseDouble(outDisVal
								.replaceAll("[,]", ""));
						// Line Items Discount
						double LineItemsDis = TotalDisVal
								- (InvDisVal + outDisValue);
						String LineItemsDisString = Double
								.toString(LineItemsDis);
						// Create values JSONArray
						JSONArray valuesarrayFinvHed = new JSONArray();

						try {
							// Create values jsonObject
							JSONObject valuesJsonFinvHed = new JSONObject();
							valuesJsonFinvHed.put("RefNo", RefNo);
							valuesJsonFinvHed.put("RefNo1", RefNo1);
							valuesJsonFinvHed.put("InvType", InvType);
							valuesJsonFinvHed.put("TxnDate", TxnDate);
							valuesJsonFinvHed.put("ManuRef", ManuRef);
							valuesJsonFinvHed.put("DealCode", DealCode);
							valuesJsonFinvHed.put("RepCode", RepCode);
							valuesJsonFinvHed.put("AreaCode", AreaCode);
							valuesJsonFinvHed.put("RouteCode", RouteCode);
							valuesJsonFinvHed.put("DebCode", DebCode);
							valuesJsonFinvHed.put("LocCode", LocCode);
							valuesJsonFinvHed.put("Remarks", Remarks);
							valuesJsonFinvHed.put("CostCode", CostCode);
							valuesJsonFinvHed.put("CurCode", CurCode);
							valuesJsonFinvHed.put("CurRate", CurRate);
							valuesJsonFinvHed.put("TxnType", TxnType);
							valuesJsonFinvHed.put("InvAmt", InvAmt);
							valuesJsonFinvHed.put("OutDis", OutDis);
							valuesJsonFinvHed.put("InvDis", InvDis);
							valuesJsonFinvHed.put("TotMkrAmt",
									TotMkrAmt.replaceAll("[,]", ""));
							valuesJsonFinvHed.put("UnOvAmt",
									UnOvAmt.replaceAll("[,]", ""));
							valuesJsonFinvHed.put("TotalDis",
									TotalDis.replaceAll("[,]", ""));
							valuesJsonFinvHed.put("TotalItmDis",
									LineItemsDisString.replaceAll("[,]", ""));
							valuesJsonFinvHed.put("TotalAmt",
									PrintFTotalAmt.replaceAll("[,]", ""));
							valuesJsonFinvHed.put("AddUser", AddUser);
							valuesJsonFinvHed.put("AddDate", AddDate);
							valuesJsonFinvHed.put("AddMach", AddMach);
							valuesJsonFinvHed.put("prtcopy", prtcopy);
							valuesJsonFinvHed.put("outDisVal", outDisVal);
							valuesJsonFinvHed.put("TranBatch", " ");
							valuesJsonFinvHed
									.put("DbName", currentUserServerDB);

							valuesarrayFinvHed.put(valuesJsonFinvHed
									.remove("[,]"));
							arFinvHed.add(valuesJsonFinvHed.toString());
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				}
			}

			if (selectInvDetailsData != null) {
				if (selectInvDetailsData.getCount() > 0) {
					while (selectInvDetailsData.moveToNext()) {
						String RefNo = selectInvDetailsData.getString(1);
						String TxnDate = selectInvDetailsData.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String TxnType = selectInvDetailsData.getString(3);
						String SeqNo = selectInvDetailsData.getString(4);
						String Itemcode = selectInvDetailsData.getString(5);
						String Txnseqno = selectInvDetailsData.getString(6);
						String SellPrice = selectInvDetailsData.getString(7);
						String BSellPrice = selectInvDetailsData.getString(8);
						String TSellPrice = selectInvDetailsData.getString(9);
						String BTSellPrice = selectInvDetailsData.getString(10);
						String CostPrice = selectInvDetailsData.getString(11);
						String CaseQty = selectInvDetailsData.getString(12);
						String Type = selectInvDetailsData.getString(13);
						String PiceQty = selectInvDetailsData.getString(14);
						String Qty = selectInvDetailsData.getString(15);
						String BalQty = selectInvDetailsData.getString(16);
						String DisPer = selectInvDetailsData.getString(17);
						String DisAmt = selectInvDetailsData.getString(18);
						String BDisAmt = selectInvDetailsData.getString(19);
						String TaxAmt = selectInvDetailsData.getString(20);
						String BTaxAmt = selectInvDetailsData.getString(21);
						String Amt = selectInvDetailsData.getString(22);
						String BAmt = selectInvDetailsData.getString(23);
						String ReaCode = selectInvDetailsData.getString(24);
						String Linkrec = selectInvDetailsData.getString(25);
						String RecordId = selectInvDetailsData.getString(26);
						String itemDescription = selectInvDetailsData
								.getString(27);
						String refInvoiceDetNo = selectInvDetailsData
								.getString(28);
						String refInvoiceDetCode = selectInvDetailsData
								.getString(29);
						String refInvitemCaseQty = selectInvDetailsData
								.getString(30);
						String invDetAddDate = selectInvDetailsData
								.getString(33);
						String itemdisper = selectInvDetailsData.getString(34);
						String itemdisperval = selectInvDetailsData
								.getString(35);
						double totlineItemDis = Double.parseDouble(BDisAmt
								.replaceAll("[,]", ""));
						double DisPerAmount = Double.parseDouble(itemdisperval
								.replaceAll("[,]", ""));
						double DisValueAmtCal = totlineItemDis - DisPerAmount;
						String DisValueAmtCalStr = Double
								.toString(DisValueAmtCal);
						String reasonCode = selectInvDetailsData.getString(36);

						// Create values JSONArray
						JSONArray valuesarrayFinvDet = new JSONArray();

						try {
							checkrall = checkrall + 1;
							// Create values jsonObject
							JSONObject valuesJsonFinvDet = new JSONObject();
							valuesJsonFinvDet.put("RefNo", refInvoiceDetCode);
							valuesJsonFinvDet.put("TxnDate", TxnDate);
							valuesJsonFinvDet.put("TxnType", TxnType);
							valuesJsonFinvDet.put("SeqNo", SeqNo);
							valuesJsonFinvDet.put("Itemcode", Itemcode);
							valuesJsonFinvDet.put("Txnseqno", Txnseqno);
							valuesJsonFinvDet.put("SellPrice",
									SellPrice.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("SellPrice",
									SellPrice.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("BSellPrice",
									BSellPrice.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("TSellPrice",
									TSellPrice.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("BTSellPrice",
									BTSellPrice.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("CostPrice",
									CostPrice.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("CaseQty",
									CaseQty.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("PiceQty",
									PiceQty.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("Type", Type);
							valuesJsonFinvDet.put("Qty",
									Qty.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("BalQty",
									BalQty.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("DisPer",
									DisPer.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("DisAmt",
									DisAmt.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("BDisAmt",
									BDisAmt.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("TaxAmt",
									TaxAmt.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("BTaxAmt",
									BTaxAmt.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("Amt",
									Amt.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("BAmt",
									BAmt.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("ReaCode", ReaCode);
							valuesJsonFinvDet.put("Linkrec", "0");
							valuesJsonFinvDet.put("DisPerAmt",
									itemdisperval.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("DisValAmt",
									DisValueAmtCalStr.replaceAll("[,]", ""));
							valuesJsonFinvDet.put("LocCode", UserLocCode);
							valuesJsonFinvDet
									.put("DbName", currentUserServerDB);
							valuesarrayFinvDet.put(valuesJsonFinvDet
									.remove("[,]"));
							arFinvDet.add(valuesJsonFinvDet.toString());

						} catch (Exception e) {
						}
					}
				}
			}
			String strFH = arFinvHed.toString();
			String strFD = arFinvDet.toString();

			if (selectInvHeadDetails.getCount() <= 0) {
				Log.v(TAG, "ARRAY 1" + strFH + "/" + strFD);
			} else {
				strFH = strFH.replace("[", "");
				strFH = strFH.replace("]", "");
				strFD = strFD.replace("[", "");
				strFD = strFD.replace("]", "");
				// PDADBWebServiceM
				HttpPost request = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/insertFInvHed");
				JSONStringer userJson = null;
				try {
					userJson = new JSONStringer().object().key("fHed")
							.value(strFH).key("fDet").value(strFD);
				} catch (Exception e) {
				}

				StringEntity entity = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String format1 = userJson.toString().replace("[", "");
					String format2 = format1.replace("]", "");
					String format3 = format2.replace("\\", "");

					String format4 = "\"fHed\":\"";
					// String ggg = ",\"fDet\":\"";
					String format5 = "\",\"fDet\":\"";

					String format6 = format3.replace(format4, "\"fHed\":[");
					String format7 = format6.replace(format5, "],\"fDet\":[");
					format7 = format7 + "}";
					String dj = format7.replace("\"}\"}", "\"}]}");

					/*
					 * Log.v(TAG, "****************************************\n");
					 * Log.v(TAG, "JSON1 =" + dj);
					 */
					entity = new StringEntity(dj, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
						"application/json"));
				entity.setContentType("application/json");
				request.setEntity(entity);

				// Send request to WCF service
				DefaultHttpClient httpClient = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse response = httpClient.execute(request);
					// Log.e("RES DJ1:", "RES DJ1:" + response.toString());
					// ===========================================================
					HttpEntity entitye = response.getEntity();
					is = entitye.getContent();
					if (is != null) {
						int resval = 200;
						try {
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader.readLine() + "\n");
							String line = "0";
							while ((line = reader.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result = sb.toString();
							String result1 = result.replace("\"", "");
							// int result1Val =
							// Integer.parseInt(result1.trim());
							Log.e("RES DJ3:", "RESULT P1:" + result1);

							if (result1.trim().equals(200)) {
								ContentValues finvhedSynUpdateVal = new ContentValues();
								finvhedSynUpdateVal.put("invhedSync", "1");
								mydb.update(INV_HEADER, finvhedSynUpdateVal,
										"invhedSync ='0'", null);

								ContentValues finvdetSynUpdateVal = new ContentValues();
								finvdetSynUpdateVal.put("invdetSync", "1");
								mydb.update(INV_DETAILS, finvdetSynUpdateVal,
										"invdetSync ='0'", null);
							}

							else {
								ContentValues finvhedSynUpdateVal = new ContentValues();
								finvhedSynUpdateVal.put("invhedSync", "1");
								mydb.update(INV_HEADER, finvhedSynUpdateVal,
										"invhedSync ='0'", null);

								ContentValues finvdetSynUpdateVal = new ContentValues();
								finvdetSynUpdateVal.put("invdetSync", "1");
								mydb.update(INV_DETAILS, finvdetSynUpdateVal,
										"invdetSync ='0'", null);

								String result12 = result.replace("\",", "");
								String result13 = result12.replace("\"", "");
								String result14 = result13.replace("\\", "");
								String[] items = result14.split(",");
								List<String> container = Arrays.asList(items);
								List<String> android = new ArrayList<String>(
										container);
								Log.e("RES DJ2:", "RESULT Array SE:" + android);
								// Getting Iterator from List
								Iterator<String> iterator = android.iterator();
								while (iterator.hasNext()) {
									String ReadRefNumbers = iterator.next();
									String QueryfinvhedSynUpdate, QueryfinvdetSynUpdate;
									Cursor finvhedSynUpdate = null, finvdetSynUpdate = null;
									try {
										QueryfinvhedSynUpdate = "SELECT * from FinvHed Where RefNo ='"
												+ ReadRefNumbers
												+ "' AND invhedSync = '0'";
										finvhedSynUpdate = mydb.rawQuery(
												QueryfinvhedSynUpdate, null);
									} catch (Exception e) {
									}
									try {
										QueryfinvdetSynUpdate = "SELECT * from FinvDet Where RefNo ='"
												+ ReadRefNumbers
												+ "' AND invdetSync = '0'";
										finvdetSynUpdate = mydb.rawQuery(
												QueryfinvdetSynUpdate, null);
									} catch (Exception e) {
									}
									if (finvhedSynUpdate != null) {
										if (finvhedSynUpdate.getCount() > 0) {
											while (finvhedSynUpdate
													.moveToNext()) {
												Log.e("RES DJ2:",
														"ReadRefNumbers HEAD IF"
																+ ReadRefNumbers);
												ContentValues finvhedSynUpdaterall = new ContentValues();
												String updatingRefNo = finvhedSynUpdate
														.getString(1);
												finvhedSynUpdaterall.put(
														"invhedSync", "0");
												mydb.update(INV_HEADER,
														finvhedSynUpdaterall,
														"RefNo ='"
																+ updatingRefNo
																+ "'", null);
											}
										}
									}
									if (finvdetSynUpdate != null) {
										if (finvdetSynUpdate.getCount() > 0) {
											while (finvdetSynUpdate
													.moveToNext()) {
												ContentValues finvdetSynUpdaterall = new ContentValues();
												String updatingRefNo = finvhedSynUpdate
														.getString(1);
												finvdetSynUpdaterall.put(
														"invdetSync", "0");
												mydb.update(INV_DETAILS,
														finvdetSynUpdaterall,
														"RefNo ='"
																+ updatingRefNo
																+ "'", null);
											}
										} else {
										}
									}

									iterator.remove(); // you should be using
														// Iterator's remove
														// method
								}
							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// *******Sales Order Invoice Uploading Start********
			if (selectOrderHeader != null) {
				if (selectOrderHeader.getCount() > 0) {
					while (selectOrderHeader.moveToNext()) {
						// FStoOrdersHedIndex = selectOrderHeader.getString(0);
						String AddMach = selectOrderHeader.getString(1);
						String AddUser = selectOrderHeader.getString(2);
						String AreaCode = selectOrderHeader.getString(3);
						String CostCode = selectOrderHeader.getString(4);
						String CurCode = selectOrderHeader.getString(5);
						String CurRate = selectOrderHeader.getString(6);
						String DealCode = selectOrderHeader.getString(7);
						String DebCode = selectOrderHeader.getString(8);
						String InvAmt = selectOrderHeader.getString(9);
						String InvDis = selectOrderHeader.getString(10);
						double InvDisVal = Double.parseDouble(InvDis
								.replaceAll("[,]", ""));
						String InvFlg = selectOrderHeader.getString(11);
						String LocCode = selectOrderHeader.getString(12);
						String ManuRef = selectOrderHeader.getString(13);
						String OutDis = selectOrderHeader.getString(14);
						String RecordId = selectOrderHeader.getString(15);
						String RefNo = selectOrderHeader.getString(16);
						String Remarks = selectOrderHeader.getString(17);
						String RepCode = selectOrderHeader.getString(18);
						String RouteCode = selectOrderHeader.getString(19);
						String TotMkrAmt = selectOrderHeader.getString(20);
						String TotalAmt = selectOrderHeader.getString(21);
						String TotalDis = selectOrderHeader.getString(22);
						double TotalDisVal = Double.parseDouble(TotalDis
								.replaceAll("[,]", ""));
						String TranBatch = selectOrderHeader.getString(23);
						String TxnType = selectOrderHeader.getString(24);
						String UnOvAmt = selectOrderHeader.getString(25);
						String prtcopy = selectOrderHeader.getString(26);
						String TxnDate = selectOrderHeader.getString(27);
						String outDisVal = selectOrderHeader.getString(30);
						UploadodAddDate = selectOrderHeader.getString(31);
						String DeliverAddDate = selectOrderHeader.getString(32);

						try {
							date = originalFormat.parse(DeliverAddDate
									.replaceAll("[-+/.^:,]", " "));
							DeliverAddDate = targetFormat.format(date);

						} catch (ParseException ex) {
						}

						// Log.v(TAG, "DDDD :" + UploadodAddDate);
						try {
							if (UploadodAddDate.equals(null)) {
								UploadodAddDate = getAddDateTimeString()
										.toString();
							}
						} catch (Exception ex) {
							UploadodAddDate = getAddDateTimeString().toString();
						}
						double outDisValue = Double.parseDouble(outDisVal
								.replaceAll("[,]", ""));
						// Line Items Discount
						double LineItemsDis = TotalDisVal
								- (InvDisVal + outDisValue);
						String LineItemsDisString = Double
								.toString(LineItemsDis);

						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}

						// Create values JSONArray
						JSONArray valuesarrayFordHed = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonFOrdHed = new JSONObject();
							valuesJsonFOrdHed.put("RefNo", RefNo);
							valuesJsonFOrdHed.put("TxnDate", TxnDate);
							valuesJsonFOrdHed.put("ManuRef", ManuRef);
							valuesJsonFOrdHed.put("DelvDate", DeliverAddDate);
							valuesJsonFOrdHed.put("DealCode", AgentDealCode);
							valuesJsonFOrdHed.put("RepCode", RepCode);
							valuesJsonFOrdHed.put("AreaCode", AreaCode);
							valuesJsonFOrdHed.put("RouteCode", RepRouteCode);
							valuesJsonFOrdHed.put("DebCode", DebCode);
							valuesJsonFOrdHed.put("LocCode", LocCode);
							valuesJsonFOrdHed.put("Remarks", Remarks);
							valuesJsonFOrdHed.put("CostCode", CostCode);
							valuesJsonFOrdHed.put("CurCode", CurCode);
							valuesJsonFOrdHed.put("CurRate", CurRate);
							valuesJsonFOrdHed.put("TxnType", TxnType);
							valuesJsonFOrdHed.put("InvAmt",
									InvAmt.replaceAll("[,]", ""));
							valuesJsonFOrdHed.put("OutDis",
									OutDis.replaceAll("[,]", ""));
							valuesJsonFOrdHed.put("InvDis",
									InvDis.replaceAll("[,]", ""));
							valuesJsonFOrdHed.put("TotMkrAmt",
									TotMkrAmt.replaceAll("[,]", ""));
							valuesJsonFOrdHed.put("UnOvAmt",
									UnOvAmt.replaceAll("[,]", ""));
							valuesJsonFOrdHed.put("TotalDis",
									TotalDis.replaceAll("[,]", ""));
							valuesJsonFOrdHed.put("TotalItmDis",
									LineItemsDisString.replaceAll("[,]", ""));
							valuesJsonFOrdHed.put("TotalAmt",
									TotalAmt.replaceAll("[,]", ""));
							valuesJsonFOrdHed.put("AddUser", AddUser);
							valuesJsonFOrdHed.put("AddMach", AddMach);
							valuesJsonFOrdHed.put("prtcopy", prtcopy);
							valuesJsonFOrdHed.put("InvFlg", InvFlg);
							valuesJsonFOrdHed.put("RecordId", RecordId);
							valuesJsonFOrdHed.put("TranBatch", TranBatch);
							valuesJsonFOrdHed.put("OutDisVal", outDisValue);
							valuesJsonFOrdHed.put("AddDate", UploadodAddDate);
							valuesJsonFOrdHed
									.put("DbName", currentUserServerDB);

							valuesarrayFordHed.put(valuesJsonFOrdHed
									.remove("[,]"));
							arFordHed.add(valuesJsonFOrdHed.toString());
						} catch (Exception Ex) {

						}

					}
				}
			}
			if (selectOrderDetails != null) {
				if (selectOrderDetails.getCount() > 0) {
					while (selectOrderDetails.moveToNext()) {
						// FStOrderDetIndex = selectOrderDetails.getString(0);
						String Amt = selectOrderDetails.getString(1);
						String BAmt = selectOrderDetails.getString(2);
						String BDisAmt = selectOrderDetails.getString(3);
						String BSellPrice = selectOrderDetails.getString(4);
						String BTSellPrice = selectOrderDetails.getString(5);
						String BTaxAmt = selectOrderDetails.getString(6);
						String BalQty = selectOrderDetails.getString(7);
						String CaseQty = selectOrderDetails.getString(8);
						String CostPrice = selectOrderDetails.getString(9);
						String DisAmt = selectOrderDetails.getString(10);
						String DisPer = selectOrderDetails.getString(11);
						String Itemcode = selectOrderDetails.getString(12);
						String PiceQty = selectOrderDetails.getString(13);
						String Qty = selectOrderDetails.getString(14);
						String ReaCode = selectOrderDetails.getString(15);
						String RecordId = selectOrderDetails.getString(16);
						String RefNo = selectOrderDetails.getString(17);
						String SellPrice = selectOrderDetails.getString(18);
						String SeqNo = selectOrderDetails.getString(19);
						String TSellPrice = selectOrderDetails.getString(20);
						String TaxAmt = selectOrderDetails.getString(21);
						String TxnType = selectOrderDetails.getString(22);
						String Txnseqno = selectOrderDetails.getString(23);
						String Type = selectOrderDetails.getString(24);
						String TxnDate = selectOrderDetails.getString(25);
						String itemdisper = selectOrderDetails.getString(27);
						String itemdisperval = selectOrderDetails.getString(28);

						double totlineItemDis = Double.parseDouble(BDisAmt
								.replaceAll("[,]", ""));
						double DisPerAmount = Double.parseDouble(itemdisperval
								.replaceAll("[,]", ""));
						double DisValueAmtCal = totlineItemDis - DisPerAmount;
						String DisValueAmtCalStr = Double
								.toString(DisValueAmtCal);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);
						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}

						// Create values JSONArray
						JSONArray valuesarrayFordDet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonFOrdDet = new JSONObject();
							valuesJsonFOrdDet.put("RefNo", RefNo);
							valuesJsonFOrdDet.put("TxnDate", TxnDate);
							valuesJsonFOrdDet.put("TxnType", TxnType);
							valuesJsonFOrdDet.put("SeqNo", SeqNo);
							valuesJsonFOrdDet.put("Itemcode", Itemcode);
							valuesJsonFOrdDet.put("Txnseqno", Txnseqno);
							valuesJsonFOrdDet.put("SellPrice",
									SellPrice.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("BSellPrice",
									BSellPrice.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("TSellPrice",
									TSellPrice.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("BTSellPrice",
									BTSellPrice.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("CostPrice",
									CostPrice.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("CaseQty", CaseQty);
							valuesJsonFOrdDet.put("Type", Type);
							valuesJsonFOrdDet.put("PiceQty",
									PiceQty.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("Qty", Qty);
							valuesJsonFOrdDet.put("BalQty",
									BalQty.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("DisPer", DisPer);
							valuesJsonFOrdDet.put("DisAmt",
									DisAmt.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("BDisAmt", BDisAmt);
							valuesJsonFOrdDet.put("TaxAmt",
									TaxAmt.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("BTaxAmt",
									BTaxAmt.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("Amt", Amt);
							valuesJsonFOrdDet.put("BAmt",
									BAmt.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("ReaCode", ReaCode);
							valuesJsonFOrdDet.put("DisPerAmt",
									itemdisperval.replaceAll("[,]", ""));
							valuesJsonFOrdDet.put("DisValAmt",
									DisValueAmtCalStr.replaceAll("[,]", ""));
							valuesJsonFOrdDet
									.put("DbName", currentUserServerDB);

							valuesarrayFordDet.put(valuesJsonFOrdDet
									.remove("[,]"));
							arFordDet.add(valuesJsonFOrdDet.toString());
						} catch (Exception ex) {

						}
					}
				}
			}
			String strFORDH = arFordHed.toString();
			String strFORDD = arFordDet.toString();

			if (selectOrderHeader.getCount() <= 0) {
				Log.v(TAG, "ARRAY 2" + strFORDH + "/" + strFORDD);
			} else {
				strFORDH = strFORDH.replace("[", "");
				strFORDH = strFORDH.replace("]", "");
				strFORDD = strFORDD.replace("[", "");
				strFORDD = strFORDD.replace("]", "");
				// PDADBWebServiceM
				HttpPost requestSOrd = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/updateFOrdHed");
				JSONStringer userJsonSOrd = null;
				try {
					userJsonSOrd = new JSONStringer().object().key("fOHed")
							.value(strFORDH).key("fODet").value(strFORDD);
				} catch (Exception e) {
				}

				StringEntity entityFSO = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatso1 = userJsonSOrd.toString().replace("[", "");
					String formatso2 = formatso1.replace("]", "");
					String formatso3 = formatso2.replace("\\", "");

					String formatso4 = "\"fOHed\":\"";
					// String ggg = ",\"fDet\":\"";
					String formatso5 = "\",\"fODet\":\"";

					String formatso6 = formatso3.replace(formatso4,
							"\"fOHed\":[");
					String formatso7 = formatso6.replace(formatso5,
							"],\"fODet\":[");
					formatso7 = formatso7 + "}";
					String sendReqSO = formatso7.replace("\"}\"}", "\"}]}");

					// Log.v(TAG, "JSON1 =" + ddddd);
					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + sendReqSO);
					entityFSO = new StringEntity(sendReqSO, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entityFSO.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
						"application/json"));
				entityFSO.setContentType("application/json");
				requestSOrd.setEntity(entityFSO);

				// Send request to WCF service
				DefaultHttpClient httpClientSO = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responseSO = httpClientSO.execute(requestSOrd);
					// Log.e("RES DJ1:", "RES DJ1:" + responseSO.toString());
					// ===========================================================
					HttpEntity entitySO = responseSO.getEntity();
					is = entitySO.getContent();
					if (is != null) {

						try {
							BufferedReader reader_so = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_so.readLine() + "\n");
							String line = "0";
							while ((line = reader_so.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_so = sb.toString();
							String result_so1 = result_so.replace("\"", "");
							if (result_so1.trim().equals(200)) {
								ContentValues fordhedSynUpdateVal = new ContentValues();
								fordhedSynUpdateVal.put("stordhedSync", "1");
								mydb.update(STOCK_ORDER_HEAD,
										fordhedSynUpdateVal,
										"stordhedSync ='0'", null);

								ContentValues forddetSynUpdateVal = new ContentValues();
								forddetSynUpdateVal.put("storddetSync", "1");
								mydb.update(STOCK_ORDER_DETAIL,
										forddetSynUpdateVal,
										"storddetSync ='0'", null);
							}

							else {
								ContentValues fordhedSynUpdateVal = new ContentValues();
								fordhedSynUpdateVal.put("stordhedSync", "1");
								mydb.update(STOCK_ORDER_HEAD,
										fordhedSynUpdateVal,
										"stordhedSync ='0'", null);

								ContentValues forddetSynUpdateVal = new ContentValues();
								forddetSynUpdateVal.put("storddetSync", "1");
								mydb.update(STOCK_ORDER_DETAIL,
										forddetSynUpdateVal,
										"storddetSync ='0'", null);

								String result12 = result_so.replace("\",", "");
								String result13 = result12.replace("\"", "");
								String result14 = result13.replace("\\", "");
								String[] items = result14.split(",");
								List<String> container = Arrays.asList(items);
								List<String> android = new ArrayList<String>(
										container);
								Log.e("RES DJ2:", "RESULT Array SE:" + android);
								// Getting Iterator from List
								Iterator<String> iterator = android.iterator();
								while (iterator.hasNext()) {
									String ReadSoRefNumbers = iterator.next();
									String QueryfOrdhedSynUpdate, QueryforddetSynUpdate;
									Cursor fordhedSynUpdate = null, forddetSynUpdate = null;
									try {
										QueryfOrdhedSynUpdate = "SELECT * from FOrdHed Where RefNo ='"
												+ ReadSoRefNumbers
												+ "' AND stordhedSync = '0'";
										fordhedSynUpdate = mydb.rawQuery(
												QueryfOrdhedSynUpdate, null);
									} catch (Exception e) {
									}
									try {
										QueryforddetSynUpdate = "SELECT * from FOrddet Where RefNo ='"
												+ ReadSoRefNumbers
												+ "' AND storddetSync = '0'";
										forddetSynUpdate = mydb.rawQuery(
												QueryforddetSynUpdate, null);
									} catch (Exception e) {
									}
									if (fordhedSynUpdate != null) {
										if (fordhedSynUpdate.getCount() > 0) {
											while (fordhedSynUpdate
													.moveToNext()) {
												ContentValues fordhedSynUpdaterall = new ContentValues();
												String updatingRefNo = fordhedSynUpdate
														.getString(16);
												fordhedSynUpdaterall.put(
														"stordhedSync", "0");
												mydb.update(STOCK_ORDER_HEAD,
														fordhedSynUpdaterall,
														"RefNo ='"
																+ updatingRefNo
																+ "'", null);
											}
										}
									}
									if (forddetSynUpdate != null) {
										if (forddetSynUpdate.getCount() > 0) {
											while (forddetSynUpdate
													.moveToNext()) {
												ContentValues forddetSynUpdaterall = new ContentValues();
												String updatingRefNo = fordhedSynUpdate
														.getString(17);
												forddetSynUpdaterall.put(
														"storddetSync", "0");
												mydb.update(STOCK_ORDER_DETAIL,
														forddetSynUpdaterall,
														"RefNo ='"
																+ updatingRefNo
																+ "'", null);
											}
										} else {
										}
									}

									iterator.remove(); // you should be using
														// Iterator's remove
														// method
								}
							}

						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// *************Upload Cancel Invoice*********
			if (selectSIcancelHedDetDetails != null) {
				if (selectSIcancelHedDetDetails.getCount() > 0) {
					while (selectSIcancelHedDetDetails.moveToNext()) {
						String RefNo = selectSIcancelHedDetDetails.getString(0);
						String RefNo1 = selectSIcancelHedDetDetails
								.getString(1);
						String InvType = selectSIcancelHedDetDetails
								.getString(2);
						String TxnDate = selectSIcancelHedDetDetails
								.getString(3);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectSIcancelHedDetDetails
								.getString(4);
						String DealCode = selectSIcancelHedDetDetails
								.getString(5);
						String RepCode = selectSIcancelHedDetDetails
								.getString(6);
						String AreaCode = selectSIcancelHedDetDetails
								.getString(7);
						String RouteCode = selectSIcancelHedDetDetails
								.getString(8);
						String DebCode = selectSIcancelHedDetDetails
								.getString(9);
						String LocCode = selectSIcancelHedDetDetails
								.getString(10);
						String Remarks = selectSIcancelHedDetDetails
								.getString(11);
						String CostCode = selectSIcancelHedDetDetails
								.getString(12);
						String CurCode = selectSIcancelHedDetDetails
								.getString(13);
						String CurRate = selectSIcancelHedDetDetails
								.getString(14);
						String TxnType = selectSIcancelHedDetDetails
								.getString(15);
						String InvAmt = selectSIcancelHedDetDetails
								.getString(16);
						String OutDis = selectSIcancelHedDetDetails
								.getString(17);
						String InvDis = selectSIcancelHedDetDetails
								.getString(18);
						String TotMkrAmt = selectSIcancelHedDetDetails
								.getString(19);
						String UnOvAmt = selectSIcancelHedDetDetails
								.getString(20);
						String TotalDis = selectSIcancelHedDetDetails
								.getString(21);
						String TotalAmt = selectSIcancelHedDetDetails
								.getString(22);
						String AddUser = selectSIcancelHedDetDetails
								.getString(23);
						String AddDateInvHead = selectSIcancelHedDetDetails
								.getString(24);
						try {
							date = originalFormat.parse(AddDateInvHead
									.replaceAll("[-+/.^:,]", " "));
							AddDateInvHead = targetFormat.format(date);

						} catch (ParseException ex) {
						}

						Log.v(TAG, "DDDD :" + UploadodAddDate);
						try {
							if (UploadodAddDate.equals(null)) {
								UploadodAddDate = getAddDateTimeString()
										.toString();
							}
						} catch (Exception ex) {
							UploadodAddDate = getAddDateTimeString().toString();
						}
						String AddMach = selectSIcancelHedDetDetails
								.getString(25);
						String prtcopy = selectSIcancelHedDetDetails
								.getString(26);
						String detRefno = selectSIcancelHedDetDetails
								.getString(27);
						String SeqNo = selectSIcancelHedDetDetails
								.getString(28);
						String Itemcode = selectSIcancelHedDetDetails
								.getString(29);
						String Txnseqno = selectSIcancelHedDetDetails
								.getString(30);
						String SellPrice = selectSIcancelHedDetDetails
								.getString(31);
						String BSellPrice = selectSIcancelHedDetDetails
								.getString(32);
						String TSellPrice = selectSIcancelHedDetDetails
								.getString(33);
						String BTSellPrice = selectSIcancelHedDetDetails
								.getString(34);
						String CostPrice = selectSIcancelHedDetDetails
								.getString(35);
						String CaseQty = selectSIcancelHedDetDetails
								.getString(36);
						String PiceQty = selectSIcancelHedDetDetails
								.getString(37);
						String Type = selectSIcancelHedDetDetails.getString(38);
						String Qty = selectSIcancelHedDetDetails.getString(39);
						String BalQty = selectSIcancelHedDetDetails
								.getString(40);
						String DisPer = selectSIcancelHedDetDetails
								.getString(41);
						String DisAmt = selectSIcancelHedDetDetails
								.getString(42);
						String BDisAmt = selectSIcancelHedDetDetails
								.getString(43);
						String DisPerAmt = selectSIcancelHedDetDetails
								.getString(44);
						String DisValAmt = selectSIcancelHedDetDetails
								.getString(45);
						String TaxAmt = selectSIcancelHedDetDetails
								.getString(46);
						String BTaxAmt = selectSIcancelHedDetDetails
								.getString(47);
						String Amt = selectSIcancelHedDetDetails.getString(48);
						String BAmt = selectSIcancelHedDetDetails.getString(49);
						String ReaCode = selectSIcancelHedDetDetails
								.getString(50);
						String Linkrec = selectSIcancelHedDetDetails
								.getString(51);

						String DelDate = selectSIcancelHedDetDetails
								.getString(24);
						try {
							date = originalFormat.parse(DelDate.replaceAll(
									"[-+/.^:,]", " "));
							DelDate = targetFormat.format(date);

						} catch (ParseException ex) {
							DelDate = "1900-01-01";
						}
						String DelType = "D";
						String DelMach = selectSIcancelHedDetDetails
								.getString(25);
						String DelUser = selectSIcancelHedDetDetails
								.getString(6);
						String DelReasn = "0";
						String Longitude = "0";
						String Latitude = "0";
						// Create values JSONArray
						JSONArray valuesarrayCanceledFHedDet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesarrayCancelSIhedDet = new JSONObject();
							valuesarrayCancelSIhedDet.put("RefNo", RefNo);
							valuesarrayCancelSIhedDet.put("RefNo1", RefNo1);
							valuesarrayCancelSIhedDet.put("InvType", InvType);
							valuesarrayCancelSIhedDet.put("TxnDate", TxnDate);
							valuesarrayCancelSIhedDet.put("ManuRef", ManuRef);
							valuesarrayCancelSIhedDet.put("DealCode", DealCode);
							valuesarrayCancelSIhedDet.put("RepCode", RepCode);
							valuesarrayCancelSIhedDet.put("AreaCode", AreaCode);
							valuesarrayCancelSIhedDet.put("RouteCode",
									RouteCode);
							valuesarrayCancelSIhedDet.put("DebCode", DebCode);
							valuesarrayCancelSIhedDet.put("LocCode", LocCode);
							valuesarrayCancelSIhedDet.put("Remarks", Remarks);
							valuesarrayCancelSIhedDet.put("CostCode", CostCode);
							valuesarrayCancelSIhedDet.put("CurCode", CurCode);
							valuesarrayCancelSIhedDet.put("CurRate", CurRate);
							valuesarrayCancelSIhedDet.put("TxnType", TxnType);
							valuesarrayCancelSIhedDet.put("InvAmt", InvAmt);
							valuesarrayCancelSIhedDet.put("OutDis", OutDis);
							valuesarrayCancelSIhedDet.put("InvDis", InvDis);
							valuesarrayCancelSIhedDet.put("TotMkrAmt",
									TotMkrAmt);
							valuesarrayCancelSIhedDet.put("UnOvAmt", UnOvAmt);
							valuesarrayCancelSIhedDet.put("TotalItmDis",
									TotalDis);
							valuesarrayCancelSIhedDet.put("TotalDis", TotalDis);
							valuesarrayCancelSIhedDet.put("TotalAmt", TotalAmt);
							valuesarrayCancelSIhedDet.put("SeqNo", SeqNo);
							valuesarrayCancelSIhedDet.put("Itemcode", Itemcode);
							valuesarrayCancelSIhedDet.put("Txnseqno", Txnseqno);
							valuesarrayCancelSIhedDet.put("SellPrice",
									SellPrice);
							valuesarrayCancelSIhedDet.put("BSellPrice",
									BSellPrice);
							valuesarrayCancelSIhedDet.put("TSellPrice",
									TSellPrice);
							valuesarrayCancelSIhedDet.put("BTSellPrice",
									BTSellPrice);
							valuesarrayCancelSIhedDet.put("CostPrice",
									CostPrice);
							valuesarrayCancelSIhedDet.put("CaseQty", CaseQty);
							valuesarrayCancelSIhedDet.put("PiceQty", PiceQty);
							valuesarrayCancelSIhedDet.put("Type", Type);
							valuesarrayCancelSIhedDet.put("Qty", Qty);
							valuesarrayCancelSIhedDet.put("BalQty", BalQty);
							valuesarrayCancelSIhedDet.put("DisPer", DisPer);
							valuesarrayCancelSIhedDet.put("DisAmt", DisAmt);
							valuesarrayCancelSIhedDet.put("BDisAmt", BDisAmt);
							valuesarrayCancelSIhedDet.put("DisPerAmt",
									DisPerAmt);
							valuesarrayCancelSIhedDet.put("DisValAmt",
									DisValAmt);
							valuesarrayCancelSIhedDet.put("TaxAmt", TaxAmt);
							valuesarrayCancelSIhedDet.put("BTaxAmt", BTaxAmt);
							valuesarrayCancelSIhedDet.put("Amt", Amt);
							valuesarrayCancelSIhedDet.put("BAmt", BAmt);
							valuesarrayCancelSIhedDet.put("ReaCode", ReaCode);
							valuesarrayCancelSIhedDet.put("AddUser", AddUser);
							valuesarrayCancelSIhedDet.put("AddDate", TxnDate);
							valuesarrayCancelSIhedDet.put("AddMach", AddMach);
							valuesarrayCancelSIhedDet.put("prtcopy", prtcopy);
							valuesarrayCancelSIhedDet.put("DelDate", TxnDate);
							valuesarrayCancelSIhedDet.put("DelType", DelType);
							valuesarrayCancelSIhedDet.put("DelMach", DelMach);
							valuesarrayCancelSIhedDet.put("DelUser", DelUser);
							valuesarrayCancelSIhedDet.put("DelReasn", DelReasn);
							valuesarrayCancelSIhedDet.put("Linkrec", Linkrec);
							valuesarrayCancelSIhedDet.put("Longitude",
									Longitude);
							valuesarrayCancelSIhedDet.put("Latitude", Latitude);
							valuesarrayCancelSIhedDet.put("DbName",
									currentUserServerDB);
							valuesarrayCanceledFHedDet
									.put(valuesarrayCancelSIhedDet
											.remove("[,]"));
							arCanceleInvHedDet.add(valuesarrayCancelSIhedDet
									.toString());

						} catch (Exception e) {

						}
					}
				}
			}
			// Log.v(TAG, "arCanceleInvHedDet:" + arCanceleInvHedDet);
			// PDADBWebServiceM

			if (selectSIcancelHedDetDetails.getCount() <= 0) {
				Log.v(TAG, "ARRAY 3" + arCanceleInvHedDet);
			} else {
				HttpPost requestIInvDet = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/insertlInvdet");
				JSONStringer userJsonlInvdet = null;
				try {
					userJsonlInvdet = new JSONStringer().object().key("fDet")
							.value(arCanceleInvHedDet);
				} catch (Exception e) {
				}

				StringEntity entitylInvdet = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatso1 = userJsonlInvdet.toString().replace("\\",
							"");
					String formatso2 = formatso1.replace("\"[{", "[{");
					String formatso3 = formatso2.replace("}]\"", "}]}");

					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + formatso3);
					entitylInvdet = new StringEntity(formatso3, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				entitylInvdet.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entitylInvdet.setContentType("application/json");
				requestIInvDet.setEntity(entitylInvdet);

				// Send request to WCF service
				DefaultHttpClient httpClientlInvdet = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responselInvdet = httpClientlInvdet
							.execute(requestIInvDet);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responselInvdet.toString());
					// ===========================================================
					HttpEntity entity_lInvdet = responselInvdet.getEntity();
					is = entity_lInvdet.getContent();
					if (is != null) {

						try {
							BufferedReader reader_lInvdet = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_lInvdet.readLine() + "\n");
							String line = "0";
							while ((line = reader_lInvdet.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_lInvdet = sb.toString();
							Log.e("RES DJ2:", "RESULT :" + result_lInvdet);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// ****************Upload Canceled Invoice Header/Details records
			// *************Upload Cancel Invoice*********
			if (selectSOcancelHedDetDetails != null) {
				if (selectSOcancelHedDetDetails.getCount() > 0) {
					while (selectSOcancelHedDetDetails.moveToNext()) {
						String RefNo = selectSOcancelHedDetDetails.getString(0);
						String TxnDate = selectSOcancelHedDetDetails
								.getString(1);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectSOcancelHedDetDetails
								.getString(2);
						String DelvDate = selectSOcancelHedDetDetails
								.getString(1);
						try {
							date = originalFormat.parse(DelvDate.replaceAll(
									"[-+/.^:,]", " "));
							DelvDate = targetFormat.format(date);

						} catch (ParseException ex) {
							DelvDate = "1900-01-01";
						}
						String DealCode = selectSOcancelHedDetDetails
								.getString(4);
						String RepCode = selectSOcancelHedDetDetails
								.getString(5);
						String AreaCode = selectSOcancelHedDetDetails
								.getString(6);
						String RouteCode = selectSOcancelHedDetDetails
								.getString(7);
						String DebCode = selectSOcancelHedDetDetails
								.getString(8);
						String LocCode = selectSOcancelHedDetDetails
								.getString(9);
						String Remarks = selectSOcancelHedDetDetails
								.getString(10);
						String CostCode = selectSOcancelHedDetDetails
								.getString(11);
						String CurCode = selectSOcancelHedDetDetails
								.getString(12);
						String CurRate = selectSOcancelHedDetDetails
								.getString(13);
						String TxnType = selectSOcancelHedDetDetails
								.getString(14);
						String InvAmt = selectSOcancelHedDetDetails
								.getString(15);
						String OutDis = selectSOcancelHedDetDetails
								.getString(16);
						String InvDis = selectSOcancelHedDetDetails
								.getString(17);
						String TotMkrAmt = selectSOcancelHedDetDetails
								.getString(18);
						String UnOvAmt = selectSOcancelHedDetDetails
								.getString(19);
						String TotalDis = selectSOcancelHedDetDetails
								.getString(20);
						String TotalAmt = selectSOcancelHedDetDetails
								.getString(21);
						String InvFlg = selectSOcancelHedDetDetails
								.getString(22);
						String SeqNo = selectSOcancelHedDetDetails
								.getString(23);
						String Itemcode = selectSOcancelHedDetDetails
								.getString(24);
						String Txnseqno = selectSOcancelHedDetDetails
								.getString(25);
						String SellPrice = selectSOcancelHedDetDetails
								.getString(26);
						String BSellPrice = selectSOcancelHedDetDetails
								.getString(27);
						String TSellPrice = selectSOcancelHedDetDetails
								.getString(28);
						String BTSellPrice = selectSOcancelHedDetDetails
								.getString(29);
						String CostPrice = selectSOcancelHedDetDetails
								.getString(30);
						String CaseQty = selectSOcancelHedDetDetails
								.getString(31);
						String PiceQty = selectSOcancelHedDetDetails
								.getString(32);
						String Type = selectSOcancelHedDetDetails.getString(33);
						String Qty = selectSOcancelHedDetDetails.getString(34);
						String BalQty = selectSOcancelHedDetDetails
								.getString(35);
						String DisPer = selectSOcancelHedDetDetails
								.getString(36);
						String DisAmt = selectSOcancelHedDetDetails
								.getString(37);
						String BDisAmt = selectSOcancelHedDetDetails
								.getString(38);
						String TaxAmt = selectSOcancelHedDetDetails
								.getString(39);
						String BTaxAmt = selectSOcancelHedDetDetails
								.getString(40);
						String Amt = selectSOcancelHedDetDetails.getString(41);
						String Bamt = selectSOcancelHedDetDetails.getString(42);
						String ReaCode = selectSOcancelHedDetDetails
								.getString(43);
						String AddUser = selectSOcancelHedDetDetails
								.getString(44);
						String ohAddDate = selectSOcancelHedDetDetails
								.getString(45);
						String AddMach = selectSOcancelHedDetDetails
								.getString(46);
						String prtcopy = selectSOcancelHedDetDetails
								.getString(47);
						String itemdisper = selectSOcancelHedDetDetails
								.getString(48);
						String itemdisperval = selectSOcancelHedDetDetails
								.getString(49);
						// Create values JSONArray
						JSONArray valuesarrayCanceledFOrdDet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesarrayCancelSOhedDet = new JSONObject();
							valuesarrayCancelSOhedDet.put("RefNo", RefNo);
							valuesarrayCancelSOhedDet.put("TxnDate", TxnDate);
							valuesarrayCancelSOhedDet.put("ManuRef", ManuRef);
							valuesarrayCancelSOhedDet.put("DelvDate", DelvDate);
							valuesarrayCancelSOhedDet.put("DealCode", DealCode);
							valuesarrayCancelSOhedDet.put("RepCode", RepCode);
							valuesarrayCancelSOhedDet.put("AreaCode", AreaCode);
							valuesarrayCancelSOhedDet.put("RouteCode",
									RouteCode);
							valuesarrayCancelSOhedDet.put("DebCode", DebCode);
							valuesarrayCancelSOhedDet.put("LocCode", LocCode);
							valuesarrayCancelSOhedDet.put("Remarks", Remarks);
							valuesarrayCancelSOhedDet.put("CostCode", CostCode);
							valuesarrayCancelSOhedDet.put("CurCode", CurCode);
							valuesarrayCancelSOhedDet.put("CurRate", CurRate);
							valuesarrayCancelSOhedDet.put("TxnType", TxnType);
							valuesarrayCancelSOhedDet.put("InvAmt", InvAmt);
							valuesarrayCancelSOhedDet.put("OutDis", OutDis);
							valuesarrayCancelSOhedDet.put("InvDis", InvDis);
							valuesarrayCancelSOhedDet.put("TotMkrAmt",
									TotMkrAmt);
							valuesarrayCancelSOhedDet.put("UnOvAmt", UnOvAmt);
							valuesarrayCancelSOhedDet.put("TotalDis", TotalDis);
							valuesarrayCancelSOhedDet.put("TotalItmDis",
									TotalDis);
							valuesarrayCancelSOhedDet.put("TotalAmt", TotalAmt);
							valuesarrayCancelSOhedDet.put("InvFlg", InvFlg);
							valuesarrayCancelSOhedDet.put("SeqNo", SeqNo);
							valuesarrayCancelSOhedDet.put("Itemcode", Itemcode);
							valuesarrayCancelSOhedDet.put("Txnseqno", Txnseqno);
							valuesarrayCancelSOhedDet.put("SellPrice",
									SellPrice);
							valuesarrayCancelSOhedDet.put("BSellPrice",
									BSellPrice);
							valuesarrayCancelSOhedDet.put("TSellPrice",
									TSellPrice);
							valuesarrayCancelSOhedDet.put("BTSellPrice",
									BTSellPrice);
							valuesarrayCancelSOhedDet.put("CostPrice",
									CostPrice);
							valuesarrayCancelSOhedDet.put("CaseQty", CaseQty);
							valuesarrayCancelSOhedDet.put("PiceQty", PiceQty);
							valuesarrayCancelSOhedDet.put("Type", Type);
							valuesarrayCancelSOhedDet.put("Qty", Qty);
							valuesarrayCancelSOhedDet.put("BalQty", BalQty);
							valuesarrayCancelSOhedDet.put("DisPer", DisPer);
							valuesarrayCancelSOhedDet.put("DisAmt", DisAmt);
							valuesarrayCancelSOhedDet.put("BDisAmt", BDisAmt);
							valuesarrayCancelSOhedDet.put("TaxAmt", TaxAmt);
							valuesarrayCancelSOhedDet.put("BTaxAmt", BTaxAmt);
							valuesarrayCancelSOhedDet.put("Amt", Amt);
							valuesarrayCancelSOhedDet.put("BAmt", Bamt);
							valuesarrayCancelSOhedDet.put("ReaCode", ReaCode);
							valuesarrayCancelSOhedDet.put("AddUser", AddUser);
							valuesarrayCancelSOhedDet.put("AddDate", ohAddDate);
							valuesarrayCancelSOhedDet.put("AddMach", AddMach);
							valuesarrayCancelSOhedDet.put("prtcopy", prtcopy);
							valuesarrayCancelSOhedDet.put("DisPerAmt",
									itemdisper);
							valuesarrayCancelSOhedDet.put("DisValAmt",
									itemdisperval);
							valuesarrayCancelSOhedDet.put("RecordId", "1");
							valuesarrayCancelSOhedDet.put("DelDate", ohAddDate);
							valuesarrayCancelSOhedDet.put("DelType", "D");
							valuesarrayCancelSOhedDet.put("DelMach", AddMach);
							valuesarrayCancelSOhedDet.put("DelUser", AddUser);
							valuesarrayCancelSOhedDet.put("DelReasn", "");
							valuesarrayCancelSOhedDet.put("DbName",
									currentUserServerDB);
							valuesarrayCanceledFOrdDet
									.put(valuesarrayCancelSOhedDet
											.remove("[,]"));
							arCanceleOrdHedDet.add(valuesarrayCancelSOhedDet
									.toString());

						} catch (Exception e) {

						}

					}
				}
			}

			if (selectSOcancelHedDetDetails.getCount() <= 0) {
				Log.v(TAG, "ARRAY 4" + arCanceleOrdHedDet);
			} else {

				HttpPost requestlOrdDet = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/insertlOrdDet");
				JSONStringer userJsonlOrdDet = null;
				try {
					userJsonlOrdDet = new JSONStringer().object().key("iDet")
							.value(arCanceleOrdHedDet);
				} catch (Exception e) {
				}

				StringEntity entitylOrdDet = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatLcso1 = userJsonlOrdDet.toString().replace(
							"\\", "");
					String formatLcso2 = formatLcso1.replace("\"[{", "[{");
					String formatLcso3 = formatLcso2.replace("}]\"", "}]}");

					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + formatLcso3);
					entitylOrdDet = new StringEntity(formatLcso3, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				entitylOrdDet.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entitylOrdDet.setContentType("application/json");
				requestlOrdDet.setEntity(entitylOrdDet);

				// Send request to WCF service
				DefaultHttpClient httpClientlOrdDet = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responselOrdDet = httpClientlOrdDet
							.execute(requestlOrdDet);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responselOrdDet.toString());
					// ===========================================================
					HttpEntity entity_lOrdDet = responselOrdDet.getEntity();
					is = entity_lOrdDet.getContent();
					if (is != null) {

						try {
							BufferedReader reader_lOrdDet = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_lOrdDet.readLine() + "\n");
							String line = "0";
							while ((line = reader_lOrdDet.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_lOrdDet = sb.toString();
							Log.e("RES DJ2:", "RESULT :" + result_lOrdDet);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// ****************Unloading Uploads
			// Handling*****************************8
			if (selectStockUnloadHeader != null) {
				if (selectStockUnloadHeader.getCount() > 0) {
					while (selectStockUnloadHeader.moveToNext()) {
						// FUnloadHedIndex =
						// selectStockUnloadHeader.getString(0);
						String RefNo = selectStockUnloadHeader.getString(1);
						String TxnDate = selectStockUnloadHeader.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectStockUnloadHeader.getString(3);
						String CostCode = selectStockUnloadHeader.getString(4);
						String Remarks = selectStockUnloadHeader.getString(5);
						String TxnType = selectStockUnloadHeader.getString(6);
						String TotalAmt = selectStockUnloadHeader.getString(7);
						double TotalAmtdou = Double.parseDouble(TotalAmt
								.replaceAll("[,]", ""));
						double FTotalAmt = TotalAmtdou + 0.00;
						String PrintFTotalAmtStl = Double.toString(FTotalAmt);
						String DelPersn = selectStockUnloadHeader.getString(8);
						String DelAdd1 = selectStockUnloadHeader.getString(9);
						String DelAdd2 = selectStockUnloadHeader.getString(10);
						String DelAdd3 = selectStockUnloadHeader.getString(11);
						String VehicalNo = selectStockUnloadHeader
								.getString(12);
						String GlPost = selectStockUnloadHeader.getString(13);
						String GlBatch = selectStockUnloadHeader.getString(14);
						String AddUser = selectStockUnloadHeader.getString(15);
						String AddDatestlh = selectStockUnloadHeader
								.getString(16);
						String AddMach = selectStockUnloadHeader.getString(17);
						String TranFlg = selectStockUnloadHeader.getString(18);
						String ItemType = selectStockUnloadHeader.getString(19);
						String IntangFlg = selectStockUnloadHeader
								.getString(21);

						JSONArray valuesarrayfUnLoadhed = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfUnLoadhed = new JSONObject();
							valuesJsonfUnLoadhed.put("RefNo", RefNo);
							valuesJsonfUnLoadhed.put("TxnDate", TxnDate);
							valuesJsonfUnLoadhed.put("ManuRef", ManuRef);
							valuesJsonfUnLoadhed.put("DealCode", AgentDealCode);
							valuesJsonfUnLoadhed.put("CostCode", "000");
							valuesJsonfUnLoadhed.put("Remarks", Remarks);
							valuesJsonfUnLoadhed.put("TxnType", TxnType);
							valuesJsonfUnLoadhed.put("TotalAmt",
									PrintFTotalAmtStl);
							valuesJsonfUnLoadhed.put("DelPersn", DelPersn);
							valuesJsonfUnLoadhed.put("DelAdd1", DelAdd1);
							valuesJsonfUnLoadhed.put("DelAdd2", DelAdd2);
							valuesJsonfUnLoadhed.put("DelAdd3", DelAdd3);
							valuesJsonfUnLoadhed.put("VehicalNo", VehicalNo);
							valuesJsonfUnLoadhed.put("GlPost", GlPost);
							valuesJsonfUnLoadhed.put("GlBatch", GlBatch);
							valuesJsonfUnLoadhed.put("AddUser", AddUser);
							valuesJsonfUnLoadhed.put("AddDate", AddDatestlh);
							valuesJsonfUnLoadhed.put("AddMach", AddMach);
							valuesJsonfUnLoadhed.put("TranFlg", TranFlg);
							valuesJsonfUnLoadhed.put("ItemType", ItemType);
							valuesJsonfUnLoadhed.put("IntangFlg", IntangFlg);
							valuesJsonfUnLoadhed.put("DbName",
									currentUserServerDB);

							valuesarrayfUnLoadhed.put(valuesJsonfUnLoadhed
									.remove("[,]"));
							arfUnLoadhed.add(valuesJsonfUnLoadhed.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			if (selectStockUnLoadDetails != null) {
				if (selectStockUnLoadDetails.getCount() > 0) {
					while (selectStockUnLoadDetails.moveToNext()) {
						// FStoUnloadDetIndex =
						// selectStockUnLoadDetails.getString(0);
						String RefNo = selectStockUnLoadDetails.getString(1);
						String TxnDate = selectStockUnLoadDetails.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String LocCode = selectStockUnLoadDetails.getString(3);
						String TxnType = selectStockUnLoadDetails.getString(4);
						String SeqNo = selectStockUnLoadDetails.getString(5);
						String ItemCode = selectStockUnLoadDetails.getString(6);
						String CaseQty = selectStockUnLoadDetails.getString(7);
						String PiceQty = selectStockUnLoadDetails.getString(8);
						String Qty = selectStockUnLoadDetails.getString(9);
						String CostPrice = selectStockUnLoadDetails
								.getString(10);
						String Amt = selectStockUnLoadDetails.getString(11);
						String RecordChecked = selectStockUnLoadDetails
								.getString(13);
						String IntangFlg = selectStockUnLoadDetails
								.getString(18);

						JSONArray valuesarrayfUnLoadDet = new JSONArray();

						try {
							// Create values jsonObject
							JSONObject valuesJsonfUnLoadDet = new JSONObject();
							valuesJsonfUnLoadDet.put("RefNo", RefNo);
							valuesJsonfUnLoadDet.put("TxnDate", TxnDate);
							valuesJsonfUnLoadDet.put("LocCode", LocCode);
							valuesJsonfUnLoadDet.put("TxnType", TxnType);
							valuesJsonfUnLoadDet.put("SeqNo", SeqNo);
							valuesJsonfUnLoadDet.put("ItemCode", ItemCode);
							valuesJsonfUnLoadDet.put("CaseQty", CaseQty);
							valuesJsonfUnLoadDet.put("PiceQty",
									PiceQty.replaceAll("[,]", ""));
							valuesJsonfUnLoadDet.put("Qty",
									Qty.replaceAll("[,]", ""));
							valuesJsonfUnLoadDet.put("CostPrice",
									CostPrice.replaceAll("[,]", ""));
							valuesJsonfUnLoadDet.put("Amt",
									Amt.replaceAll("[,]", ""));
							valuesJsonfUnLoadDet.put("RecordChecked",
									RecordChecked);
							valuesJsonfUnLoadDet.put("IntangFlg", IntangFlg);
							valuesJsonfUnLoadDet.put("DbName",
									currentUserServerDB);
							valuesarrayfUnLoadDet.put(valuesJsonfUnLoadDet
									.remove("[,]"));
							arfUnLoadDet.add(valuesJsonfUnLoadDet.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}

			String strFHUnload = arfUnLoadhed.toString();
			String strFDUnload = arfUnLoadDet.toString();

			if (selectStockUnloadHeader.getCount() <= 0) {
				Log.v(TAG, "ARRAY 5" + strFHUnload + "/" + strFDUnload);
			} else {

				strFHUnload = strFHUnload.replace("[", "");
				strFHUnload = strFHUnload.replace("]", "");
				strFDUnload = strFDUnload.replace("[", "");
				strFDUnload = strFDUnload.replace("]", "");
				// PDADBWebServiceM
				HttpPost requestfUnLoad = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/insertfUnLoadhed");
				JSONStringer userJsonUnload = null;
				try {
					userJsonUnload = new JSONStringer().object().key("fULHed")
							.value(strFHUnload).key("fULDet")
							.value(strFDUnload);
				} catch (Exception e) {
				}

				StringEntity entityunload = null;
				try {
					// String repval = userJsonUnload.toString() + "}" +
					// ",UTF-8";
					String formatunload1 = userJsonUnload.toString().replace(
							"[", "");
					String formatunload2 = formatunload1.replace("]", "");
					String formatunload3 = formatunload2.replace("\\", "");

					String format4unload = "\"fULHed\":\"";
					String format5unloadunload = "\",\"fULDet\":\"";

					String format6unload = formatunload3.replace(format4unload,
							"\"fULHed\":[");
					String format7unload = format6unload.replace(
							format5unloadunload, "],\"fULDet\":[");
					format7unload = format7unload + "}";
					String djunload = format7unload.replace("\"}\"}", "\"}]}");

					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + djunload);
					entityunload = new StringEntity(djunload, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entityunload.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entityunload.setContentType("application/json");
				requestfUnLoad.setEntity(entityunload);

				// Send requestfUnLoad to WCF service
				DefaultHttpClient httpClientunload = new DefaultHttpClient();

				try {
					Log.e("responseunload", "connect");
					HttpResponse responseunload = httpClientunload
							.execute(requestfUnLoad);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responseunload.toString());
					// ===========================================================
					HttpEntity entityunloade = responseunload.getEntity();
					is = entityunloade.getContent();
					if (is != null) {

						try {
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader.readLine() + "\n");
							String line = "0";
							while ((line = reader.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result = sb.toString();
							String result1 = result.replace("\"", "");
							
							if(result1.trim().equals(200)){
								ContentValues unloadhedSynUpdateVal = new ContentValues();
								unloadhedSynUpdateVal.put("stlhedunSync", "1");
								mydb.update(STOCK_LOAD_HEADUN, unloadhedSynUpdateVal, "stlhedunSync ='0'", null);
								
								ContentValues unloaddetSynUpdateVal = new ContentValues();
								unloaddetSynUpdateVal.put("stldetunSync", "1");
								mydb.update(STOCK_LOAD_DETAILUN, unloaddetSynUpdateVal, "stldetunSync ='0'", null);
							}
						
								else{
								ContentValues unloadhedSynUpdateVal = new ContentValues();
								unloadhedSynUpdateVal.put("stlhedunSync", "1");
								mydb.update(STOCK_LOAD_HEADUN, unloadhedSynUpdateVal, "stlhedunSync ='0'", null);
								
								ContentValues unloaddetSynUpdateVal = new ContentValues();
								unloaddetSynUpdateVal.put("stldetunSync", "1");
								mydb.update(STOCK_LOAD_DETAILUN, unloaddetSynUpdateVal, "stldetunSync ='0'", null);
								
								
								
								String result12 = result1.replace("\",", "");
								String result13 = result12.replace("\"", "");
								String result14 = result13.replace("\\", "");
								String [] items = result14.split(",");
								List<String> container = Arrays.asList(items);
								List<String> android = new ArrayList<String>(container);
								Log.e("RES DJ2:", "RESULT Array SE:" + android);
								// Getting Iterator from List
								Iterator<String> iterator = android.iterator();
								while (iterator.hasNext()) {
									String ReadUnRefNumbers = iterator.next();
									String QueryfUnloadhedSynUpdate,QueryfunloaddetSynUpdate;
									Cursor funloadhedSynUpdate = null,funloaddetSynUpdate = null;
									try {
										QueryfUnloadhedSynUpdate = "SELECT * from fUnLoadhed Where RefNo ='"+ ReadUnRefNumbers +"' AND stlhedunSync = '0'";
										funloadhedSynUpdate = mydb.rawQuery(QueryfUnloadhedSynUpdate, null);
									} catch (Exception e) {
									}
									try {
										QueryfunloaddetSynUpdate = "SELECT * from fUnLoadDet Where RefNo ='"+ ReadUnRefNumbers +"' AND stldetunSync = '0'";
										funloaddetSynUpdate = mydb.rawQuery(QueryfunloaddetSynUpdate, null);
									} catch (Exception e) {
									}
									if (funloadhedSynUpdate != null) {
										if (funloadhedSynUpdate.getCount() > 0) {
											while (funloadhedSynUpdate.moveToNext()) {
												ContentValues funloadhedSynUpdaterall = new ContentValues();
												String updatingRefNoUnload =  funloadhedSynUpdate.getString(1);
												funloadhedSynUpdaterall.put("stlhedunSync", "0");
												mydb.update(STOCK_LOAD_HEADUN, funloadhedSynUpdaterall, "RefNo ='" + updatingRefNoUnload + "'", null);
											}
										}
									}
									if (funloaddetSynUpdate != null) {
										if (funloaddetSynUpdate.getCount() > 0) {
											while (funloaddetSynUpdate.moveToNext()) {
												ContentValues funloaddetSynUpdaterall = new ContentValues();
												String updatingRefNoUnload =  funloadhedSynUpdate.getString(1);
												funloaddetSynUpdaterall.put("stldetunSync", "0");
												mydb.update(STOCK_LOAD_DETAILUN, funloaddetSynUpdaterall, "RefNo ='" + updatingRefNoUnload + "'", null);
											}
										}
										else{
										}
									}
									
									iterator.remove(); // you should be using Iterator's remove method
								}
							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// ******Uploading Invoice Receipt Details****

			if (selectReceiptHeadDetails != null) {
				if (selectReceiptHeadDetails.getCount() > 0) {
					while (selectReceiptHeadDetails.moveToNext()) {
						// FReceiptHedIndex =
						// selectReceiptHeadDetails.getString(0);
						String RefNo = selectReceiptHeadDetails.getString(1);
						String ManuRef = selectReceiptHeadDetails.getString(2);
						String SaleRefNo = selectReceiptHeadDetails
								.getString(3);
						String RepCode = selectReceiptHeadDetails.getString(4);
						String TxnType = selectReceiptHeadDetails.getString(5);
						String Chqno = selectReceiptHeadDetails.getString(6);
						String ChqDate = selectReceiptHeadDetails.getString(7);
						try {
							date = originalFormat.parse(ChqDate.replaceAll(
									"[-+/.^:,]", " "));
							ChqDate = targetFormat.format(date);

						} catch (ParseException ex) {
							ChqDate = "1900-01-01";
						}
						String TxnDate = selectReceiptHeadDetails.getString(8);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							// Log.v(TAG,"Old Format :"+
							// originalFormat.format(date));
							// Log.v(TAG,"New Format :" +
							// targetFormat.format(date));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String CurCode = selectReceiptHeadDetails.getString(9);
						String CurRate = selectReceiptHeadDetails.getString(10);
						String DebCode = selectReceiptHeadDetails.getString(11);
						String TotalAmt = selectReceiptHeadDetails
								.getString(12);
						String BTotalAmt = selectReceiptHeadDetails
								.getString(13);
						String BankCur = selectReceiptHeadDetails.getString(14);
						String BankRate = selectReceiptHeadDetails
								.getString(15);
						String BankAmt = selectReceiptHeadDetails.getString(16);
						String BankCharge = selectReceiptHeadDetails
								.getString(17);
						String BBankChg = selectReceiptHeadDetails
								.getString(18);
						String GnLsCal = selectReceiptHeadDetails.getString(19);
						String DbAcc = selectReceiptHeadDetails.getString(20);
						String PayType = selectReceiptHeadDetails.getString(21);
						String PrtCopy = selectReceiptHeadDetails.getString(22);
						String GlPost = selectReceiptHeadDetails.getString(23);
						String Remarks = selectReceiptHeadDetails.getString(24);
						String CardSlipNo = selectReceiptHeadDetails
								.getString(25);
						String ExpDate = selectReceiptHeadDetails.getString(26);
						try {
							date = originalFormat.parse(ExpDate.replaceAll(
									"[-+/.^:,]", " "));
							// Log.v(TAG,"Old Format :"+
							// originalFormat.format(date));
							// Log.v(TAG,"New Format :" +
							// targetFormat.format(date));
							ExpDate = targetFormat.format(date);
						} catch (ParseException ex) {
							ExpDate = "1900-01-01";
						}
						String CrdTypCode = selectReceiptHeadDetails
								.getString(27);
						String CCBankAmt = selectReceiptHeadDetails
								.getString(28);
						String GlBatch = selectReceiptHeadDetails.getString(29);
						String AddUser = selectReceiptHeadDetails.getString(30);
						String AddMach = selectReceiptHeadDetails.getString(31);
						String AddDate = selectReceiptHeadDetails.getString(32);
						try {
							date = originalFormat.parse(AddDate.replaceAll(
									"[-+/.^:,]", " "));
							// Log.v(TAG,"Old Format :"+
							// originalFormat.format(date));
							// Log.v(TAG,"New Format :" +
							// targetFormat.format(date));
							AddDate = targetFormat.format(date);
						} catch (ParseException ex) {
							AddDate = "1900-01-01";
						}

						JSONArray valuesarrayfDRecHed = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfDRecHed = new JSONObject();
							valuesJsonfDRecHed.put("RefNo", RefNo);
							valuesJsonfDRecHed.put("ManuRef", ManuRef);
							valuesJsonfDRecHed.put("SaleRefNo", SaleRefNo);
							valuesJsonfDRecHed.put("RepCode", RepCode);
							valuesJsonfDRecHed.put("TxnType", TxnType);
							valuesJsonfDRecHed.put("Chqno", Chqno);
							valuesJsonfDRecHed.put("ChqDate", ChqDate);
							valuesJsonfDRecHed.put("TxnDate", TxnDate);
							valuesJsonfDRecHed.put("CurCode", "LKR");
							valuesJsonfDRecHed.put("CurRate", CurRate);
							valuesJsonfDRecHed.put("DebCode", DebCode);
							valuesJsonfDRecHed.put("TotalAmt", "0.0");
							valuesJsonfDRecHed.put("BTotalAmt", "0.0");
							valuesJsonfDRecHed.put("BankCur", "LKR");
							valuesJsonfDRecHed.put("BankRate", BankRate);
							valuesJsonfDRecHed.put("BankAmt",
									BankAmt.replaceAll("[,]", ""));
							valuesJsonfDRecHed.put("BankCharge",
									BankCharge.replaceAll("[,]", ""));
							valuesJsonfDRecHed.put("BBankChg",
									BBankChg.replaceAll("[,]", ""));
							valuesJsonfDRecHed.put("GnLsCal", GnLsCal);
							valuesJsonfDRecHed.put("DbAcc", "00000001-000");
							valuesJsonfDRecHed.put("PayType", PayType);
							valuesJsonfDRecHed.put("PrtCopy", PrtCopy);
							valuesJsonfDRecHed.put("GlPost", GlPost);
							valuesJsonfDRecHed.put("Remarks", Remarks);
							valuesJsonfDRecHed.put("CardSlipNo", CardSlipNo);
							valuesJsonfDRecHed.put("ExpDate", ExpDate);
							valuesJsonfDRecHed.put("CrdTypCode", CrdTypCode);
							valuesJsonfDRecHed.put("CCBankAmt", CCBankAmt);
							valuesJsonfDRecHed.put("GlBatch", GlBatch);
							valuesJsonfDRecHed.put("AddUser", AddUser);
							valuesJsonfDRecHed.put("AddMach", AddMach);
							valuesJsonfDRecHed.put("AddDate", AddDate);
							valuesJsonfDRecHed.put("DbName",
									currentUserServerDB);

							valuesarrayfDRecHed.put(valuesJsonfDRecHed
									.remove("[,]"));
							arfDRecHed.add(valuesJsonfDRecHed.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			if (selectInvReceiptDetails != null) {
				if (selectInvReceiptDetails.getCount() > 0) {
					while (selectInvReceiptDetails.moveToNext()) {

						// FReceiptDetIndex =
						// selectInvReceiptDetails.getString(0);
						String RefNo = selectInvReceiptDetails.getString(1);
						String RefNo1 = selectInvReceiptDetails.getString(2);
						String SaleRefNo = selectInvReceiptDetails.getString(3);
						String ManuRef = selectInvReceiptDetails.getString(4);
						String TxnType = selectInvReceiptDetails.getString(5);
						String TxnDate = selectInvReceiptDetails.getString(6);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String DtxnDate = selectInvReceiptDetails.getString(7);
						try {
							date = originalFormat.parse(DtxnDate.replaceAll(
									"[-+/.^:,]", " "));
							DtxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							DtxnDate = "1900-01-01";
						}
						String DtxnType = selectInvReceiptDetails.getString(8);
						String DCurCode = selectInvReceiptDetails.getString(9);
						String DCurRate = selectInvReceiptDetails.getString(10);
						String OCurRate = selectInvReceiptDetails.getString(11);
						String RepCode = selectInvReceiptDetails.getString(12);
						String Amt = selectInvReceiptDetails.getString(13);
						String BAmt = selectInvReceiptDetails.getString(14);
						String GainLosAmt = selectInvReceiptDetails
								.getString(15);
						String BnkChgs = selectInvReceiptDetails.getString(16);
						String BBnkChgs = selectInvReceiptDetails.getString(17);
						String AloAmt = selectInvReceiptDetails.getString(18);
						String OvPayAmt = selectInvReceiptDetails.getString(19);
						String OvPayBal = selectInvReceiptDetails.getString(20);

						JSONArray valuesarrayfDRecDet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfDRecDet = new JSONObject();
							valuesJsonfDRecDet.put("RefNo", RefNo);
							valuesJsonfDRecDet.put("RefNo1", RefNo1);
							valuesJsonfDRecDet.put("SaleRefNo", SaleRefNo);
							valuesJsonfDRecDet.put("ManuRef", ManuRef);
							valuesJsonfDRecDet.put("TxnType", TxnType);
							valuesJsonfDRecDet.put("TxnDate", TxnDate);
							valuesJsonfDRecDet.put("DtxnDate", DtxnDate);
							valuesJsonfDRecDet.put("DtxnType", DtxnType);
							valuesJsonfDRecDet.put("DCurCode", "LKR");
							valuesJsonfDRecDet.put("DCurRate",
									DCurRate.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("OCurRate",
									OCurRate.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("RepCode", RepCode);
							valuesJsonfDRecDet.put("Amt",
									Amt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("BAmt",
									BAmt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("GainLosAmt",
									GainLosAmt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("BnkChgs",
									BnkChgs.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("BBnkChgs",
									BBnkChgs.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("AloAmt",
									AloAmt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("OvPayAmt",
									OvPayAmt.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("OvPayBal",
									OvPayBal.replaceAll("[,]", ""));
							valuesJsonfDRecDet.put("DbName",
									currentUserServerDB);

							valuesarrayfDRecDet.put(valuesJsonfDRecDet
									.remove("[,]"));
							arfDRecDet.add(valuesJsonfDRecDet.toString());

						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}
			}
			String strfDRecHed = arfDRecHed.toString();
			String strfDRecDet = arfDRecDet.toString();
			if (selectReceiptHeadDetails.getCount() <= 0) {
				Log.v(TAG, "ARRAY 6" + strfDRecHed + "/" + strfDRecDet);
			} else {

				strfDRecHed = strfDRecHed.replace("[", "");
				strfDRecHed = strfDRecHed.replace("]", "");
				strfDRecDet = strfDRecDet.replace("[", "");
				strfDRecDet = strfDRecDet.replace("]", "");
				// PDADBWebServiceM
				HttpPost requestfDRec = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/insertfDRecHed");
				JSONStringer userJsonfDRec = null;
				try {
					userJsonfDRec = new JSONStringer().object().key("fDRHed")
							.value(strfDRecHed).key("fDRDet")
							.value(strfDRecDet);
				} catch (Exception e) {
				}

				StringEntity entityfDRec = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatfdr1 = userJsonfDRec.toString().replace("[",
							"");
					String formatfdr2 = formatfdr1.replace("]", "");
					String formatfdr3 = formatfdr2.replace("\\", "");

					String formatfdr4 = "\"fDRHed\":\"";
					String formatfdr5 = "\",\"fDRDet\":\"";

					String formatfdr6 = formatfdr3.replace(formatfdr4,
							"\"fDRHed\":[");
					String formatfdr7 = formatfdr6.replace(formatfdr5,
							"],\"fDRDet\":[");
					formatfdr7 = formatfdr7 + "}";
					String sendReqfDRec = formatfdr7.replace("\"}\"}", "\"}]}");

					// Log.v(TAG, "JSON1 =" + ddddd);
					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + sendReqfDRec);
					entityfDRec = new StringEntity(sendReqfDRec, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entityfDRec.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entityfDRec.setContentType("application/json");
				requestfDRec.setEntity(entityfDRec);

				// Send request to WCF service
				DefaultHttpClient httpClientfDRec = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responsefDRec = httpClientfDRec
							.execute(requestfDRec);
					HttpEntity entityfDRecEntity = responsefDRec.getEntity();
					is = entityfDRecEntity.getContent();
					if (is != null) {

						try {
							BufferedReader reader_fDRec = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_fDRec.readLine() + "\n");
							String line = "0";
							while ((line = reader_fDRec.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_fDRec = sb.toString();
							String result_fDRec1 = result_fDRec.replace("\"",
									"");
							if (result_fDRec1.equals("200")) {
								Log.e("RES DJ2:", "RESULT :" + result_fDRec1);
								if (selectReceiptHeadDetails != null) {
									if (selectReceiptHeadDetails.getCount() > 0) {
										while (selectReceiptHeadDetails
												.moveToNext()) {
											ContentValues ReceiptHeadSynUpdateVal = new ContentValues();
											String updatingRefNo = selectReceiptHeadDetails
													.getString(1);
											ReceiptHeadSynUpdateVal.put(
													"recipthedSync", "1");
											mydb.update(RECEIPT_HEADER,
													ReceiptHeadSynUpdateVal,
													"RefNo ='" + updatingRefNo
															+ "'", null);

										}
									}
								}

								if (selectInvReceiptDetails != null) {
									if (selectInvReceiptDetails.getCount() > 0) {
										while (selectInvReceiptDetails
												.moveToNext()) {
											ContentValues ReceiptDetailsSynUpdateVal = new ContentValues();
											String updatingRefNo = selectInvReceiptDetails
													.getString(1);
											ReceiptDetailsSynUpdateVal.put(
													"reciptdetSync", "1");
											mydb.update(RECEIPT_DETAILS,
													ReceiptDetailsSynUpdateVal,
													"RefNo ='" + updatingRefNo
															+ "'", null);
										}
									}
								}
							} else {
								Log.e("RES DJ2:", "RESULT :" + result_fDRec);
							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// ****************************************************************
			if (selectStockfDamhed != null) {
				if (selectStockfDamhed.getCount() > 0) {
					while (selectStockfDamhed.moveToNext()) {
						// FUnloadHedIndex =
						// selectStockfDamhed.getString(0);
						String RefNo = selectStockfDamhed.getString(1);
						String TxnDate = selectStockfDamhed.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String ManuRef = selectStockfDamhed.getString(3);
						String DealCode = selectStockfDamhed.getString(4);
						String Remarks = selectStockfDamhed.getString(5);
						String TxnType = selectStockfDamhed.getString(6);
						String TotalAmt = selectStockfDamhed.getString(7);
						String CostCode = selectStockfDamhed.getString(8);
						String ReaCode = selectStockfDamhed.getString(9);
						String GlPost = selectStockfDamhed.getString(10);
						String GlBatch = selectStockfDamhed.getString(11);
						String AddUser = selectStockfDamhed.getString(12);
						String AddDate = selectStockfDamhed.getString(13);
						String AddMach = selectStockfDamhed.getString(14);
						String ItemType = selectStockfDamhed.getString(15);

						JSONArray valuesarrayfDamhed = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfDamhed = new JSONObject();
							valuesJsonfDamhed.put("RefNo", RefNo);
							valuesJsonfDamhed.put("TxnDate", TxnDate);
							valuesJsonfDamhed.put("ManuRef", ManuRef);
							valuesJsonfDamhed.put("DealCode", AgentDealCode);
							valuesJsonfDamhed.put("Remarks", Remarks);
							valuesJsonfDamhed.put("TxnType", TxnType);
							valuesJsonfDamhed.put("TotalAmt",
									TotalAmt.replaceAll("[,]", ""));
							valuesJsonfDamhed.put("CostCode", "000");
							valuesJsonfDamhed.put("ReaCode", ReaCode);
							valuesJsonfDamhed.put("GlPost", GlPost);
							valuesJsonfDamhed.put("GlBatch", GlBatch);
							valuesJsonfDamhed.put("AddUser", AddUser);
							valuesJsonfDamhed.put("AddDate", AddDate);
							valuesJsonfDamhed.put("AddMach", AddMach);
							valuesJsonfDamhed.put("ItemType", ItemType);
							valuesJsonfDamhed
									.put("DbName", currentUserServerDB);

							valuesarrayfDamhed.put(valuesJsonfDamhed
									.remove("[,]"));
							arfDamHed.add(valuesJsonfDamhed.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			if (selectStockfDamDet != null) {
				if (selectStockfDamDet.getCount() > 0) {
					while (selectStockfDamDet.moveToNext()) {
						// FDamageDetIndex = selectStockfDamDet.getString(0);
						String RefNo = selectStockfDamDet.getString(1);
						String TxnDate = selectStockfDamDet.getString(2);
						try {
							date = originalFormat.parse(TxnDate.replaceAll(
									"[-+/.^:,]", " "));
							TxnDate = targetFormat.format(date);

						} catch (ParseException ex) {
							TxnDate = "1900-01-01";
						}
						String LocCode = selectStockfDamDet.getString(3);
						String TxnType = selectStockfDamDet.getString(4);
						String SeqNo = selectStockfDamDet.getString(5);
						String ItemCode = selectStockfDamDet.getString(6);
						String CaseQty = selectStockfDamDet.getString(7);
						String PiceQty = selectStockfDamDet.getString(8);
						String Qty = selectStockfDamDet.getString(9);
						String CostPrice = selectStockfDamDet.getString(10);
						String Amt = selectStockfDamDet.getString(11);
						String reaCode = selectStockfDamDet.getString(17);

						JSONArray valuesarrayfDamdet = new JSONArray();
						try {
							// Create values jsonObject
							JSONObject valuesJsonfDamdet = new JSONObject();
							valuesJsonfDamdet.put("RefNo", RefNo);
							valuesJsonfDamdet.put("TxnDate", TxnDate);
							valuesJsonfDamdet.put("LocCode", LocCode);
							valuesJsonfDamdet.put("TxnType", TxnType);
							valuesJsonfDamdet.put("SeqNo", SeqNo);
							valuesJsonfDamdet.put("ItemCode", ItemCode);
							valuesJsonfDamdet.put("CaseQty", CaseQty);
							valuesJsonfDamdet.put("PiceQty",
									PiceQty.replaceAll("[,]", ""));
							valuesJsonfDamdet.put("Qty", Qty);
							valuesJsonfDamdet.put("CostPrice",
									CostPrice.replaceAll("[,]", ""));
							valuesJsonfDamdet.put("Amt",
									Amt.replaceAll("[,]", ""));
							valuesJsonfDamdet.put("ReaCode", reaCode);
							valuesJsonfDamdet
									.put("DbName", currentUserServerDB);

							valuesarrayfDamdet.put(valuesJsonfDamdet
									.remove("[,]"));
							arfDamDet.add(valuesJsonfDamdet.toString());
						} catch (JSONException e) {

							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			String strfDamHed = arfDamHed.toString();
			String strfDamDet = arfDamDet.toString();
			if (selectStockfDamhed.getCount() <= 0) {
				Log.v(TAG, "ARRAY 7" + strfDamHed + "/" + strfDamDet);
			} else {

				strfDamHed = strfDamHed.replace("[", "");
				strfDamHed = strfDamHed.replace("]", "");
				strfDamDet = strfDamDet.replace("[", "");
				strfDamDet = strfDamDet.replace("]", "");
				// PDADBWebServiceM
				HttpPost requestfDam = new HttpPost(
						connectionURL
								+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/insertfDamHed");
				JSONStringer userJsonfDam = null;
				try {
					userJsonfDam = new JSONStringer().object().key("fDhed")
							.value(strfDamHed).key("fDDet").value(strfDamDet);
				} catch (Exception e) {
				}

				StringEntity entityfDam = null;
				try {
					// String repval = userJson.toString() + "}" + ",UTF-8";
					String formatfdam1 = userJsonfDam.toString().replace("[",
							"");
					String formatfdam2 = formatfdam1.replace("]", "");
					String formatfdam3 = formatfdam2.replace("\\", "");

					String formatfdam4 = "\"fDhed\":\"";
					String formatfdam5 = "\",\"fDDet\":\"";

					String formatfdam6 = formatfdam3.replace(formatfdam4,
							"\"fDhed\":[");
					String formatfdam7 = formatfdam6.replace(formatfdam5,
							"],\"fDDet\":[");
					formatfdam7 = formatfdam7 + "}";
					String sendReqfDamage = formatfdam7.replace("\"}\"}",
							"\"}]}");
					Log.v(TAG, "****************************************\n");
					Log.v(TAG, "JSON1 =" + sendReqfDamage);
					entityfDam = new StringEntity(sendReqfDamage, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				entityfDam.setContentEncoding(new BasicHeader(
						HTTP.CONTENT_TYPE, "application/json"));
				entityfDam.setContentType("application/json");
				requestfDam.setEntity(entityfDam);

				// Send request to WCF service
				DefaultHttpClient httpClientfDamRec = new DefaultHttpClient();

				try {
					Log.e("response", "connect");
					HttpResponse responsefDamRec = httpClientfDamRec
							.execute(requestfDam);
					// Log.e("RES DJ1:", "RES DJ1:" +
					// responsefDamRec.toString());
					// ===========================================================
					HttpEntity entityfDamEntity = responsefDamRec.getEntity();
					is = entityfDamEntity.getContent();
					if (is != null) {

						try {
							BufferedReader reader_fDamRec = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader_fDamRec.readLine() + "\n");
							String line = "0";
							while ((line = reader_fDamRec.readLine()) != null) {
								sb.append(line + "\n");
							}
							is.close();
							String result_fDamRec = sb.toString();
							String result_fDamRec1 = result_fDamRec.replace(
									"\"", "");
							if (result_fDamRec1.equals("200")) {
								Log.e("RES DJ2:", "RESULT :" + result_fDamRec1);
								if (selectStockfDamhed != null) {
									if (selectStockfDamhed.getCount() > 0) {
										while (selectStockfDamhed.moveToNext()) {
											ContentValues fDamhedSynUpdateVal = new ContentValues();
											String updatingRefNo = selectStockfDamhed
													.getString(1);
											fDamhedSynUpdateVal.put(
													"stldmhedSync", "1");
											mydb.update(STOCK_LOAD_HEADDAM,
													fDamhedSynUpdateVal,
													"RefNo ='" + updatingRefNo
															+ "'", null);

										}
									}
								}

								if (selectStockfDamDet != null) {
									if (selectStockfDamDet.getCount() > 0) {
										while (selectStockfDamDet.moveToNext()) {
											ContentValues fDamdetSynUpdateVal = new ContentValues();
											String updatingRefNo = selectStockfDamDet
													.getString(1);
											fDamdetSynUpdateVal.put(
													"stldmdetSync", "1");
											mydb.update(STOCK_LOAD_DETAILDAM,
													fDamdetSynUpdateVal,
													"RefNo ='" + updatingRefNo
															+ "'", null);
										}
									}
								}
							} else {
								Log.e("RES DJ2:", "RESULT :" + result_fDamRec);
							}

						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_Application_Manage_Tools.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPLOAD STATUS");
			// Setting Dialog Message
			alertDialog.setMessage("Uploading Completed....");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	protected void dropCurrentTables() {
		// TODO Auto-generated method stub
		mydb.execSQL("DROP TABLE IF EXISTS fArea");
		mydb.execSQL("DROP TABLE IF EXISTS fCompanySetting");
		mydb.execSQL("DROP TABLE IF EXISTS fControl");
		mydb.execSQL("DROP TABLE IF EXISTS fDebtor");
		mydb.execSQL("DROP TABLE IF EXISTS fItemLoc");
		mydb.execSQL("DROP TABLE IF EXISTS fLocation");
		mydb.execSQL("DROP TABLE IF EXISTS fItemPri");
		mydb.execSQL("DROP TABLE IF EXISTS fItems");
		mydb.execSQL("DROP TABLE IF EXISTS FCompanyBranch");
		mydb.execSQL("DROP TABLE IF EXISTS fSalRep");
		mydb.execSQL("DROP TABLE IF EXISTS fReason");
		mydb.execSQL("DROP TABLE IF EXISTS fRoute");
		mydb.execSQL("DROP TABLE IF EXISTS fRouteDet");
		mydb.execSQL("DROP TABLE IF EXISTS fBank");
		mydb.execSQL("DROP TABLE IF EXISTS fExpense");
		mydb.execSQL("DROP TABLE IF EXISTS fTown");
		mydb.execSQL("DROP TABLE IF EXISTS FMerch");
		mydb.execSQL("DROP TABLE IF EXISTS fDealer");
		mydb.execSQL("DROP TABLE IF EXISTS FTrgCapUL");
		mydb.execSQL("DROP TABLE IF EXISTS fType");
		mydb.execSQL("DROP TABLE IF EXISTS fSubBrand");
		mydb.execSQL("DROP TABLE IF EXISTS fGroup");
		mydb.execSQL("DROP TABLE IF EXISTS fSku");
		mydb.execSQL("DROP TABLE IF EXISTS fbrand");
	}

	// get server DB Name
	private void getServerDBName() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUserSettings = null;
		try {
			curUserSettings = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}

		if (curUserSettings != null) {
			if (curUserSettings.getCount() > 0) {
				while (curUserSettings.moveToNext()) {
					serverDBName = curUserSettings.getString(7);
				}
			}
		}
	}

	// Retrieve Current URL
	private void getConnectionUrl() {
		// TODO Auto-generated method stub
		Cursor getserverurl = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			getserverurl = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (getserverurl != null) {
			if (getserverurl.getCount() > 0) {
				while (getserverurl.moveToNext()) {
					connectionURL = getserverurl.getString(1);
				}
			}
		}
		mydb.close();
	}

	protected void createMasterTables() {
		// TODO Auto-generated method stub
		try {
			Log.v(TAG, "onCreate Call");

			mydb.execSQL("create table if not exists "
					+ SALES_DEALER
					+ "(_id integer primary key autoincrement,DealCode text not null,DealName text not null,DealAdd1 text not null,DealAdd2 text not null,DealAdd3 text not null,DealTele text not null,DealMob text not null,DealEMail text not null,Status text not null,Distance text not null,DealGdCode text not null,CusTypCode text not null,AddUser text not null,AddDate text not null,AddMach text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ YEARS_LIST
					+ "(year_id integer primary key autoincrement,yearname text not null);");

			mydb.execSQL("create table if not exists "
					+ MONTH_LIST
					+ "(month_id integer primary key autoincrement,monthindex text not null,monthname text not null);");

			mydb.execSQL("create table if not exists "
					+ SERVER_DETAILS
					+ "(server_id integer primary key autoincrement,serverurl text not null,portval text not null,serverdbname text not null,activeproperty text not null);");

			mydb.execSQL("create table if not exists "
					+ SERVER_DB_LIST
					+ "(sdb_id integer primary key autoincrement,sdbname text not null);");
			
			mydb.execSQL("create table if not exists "
					+ USER_SETTINGS
					+ "(_id integer primary key autoincrement,username text not null,lrepprefix text not null,lreploccode text not null,currentStOrdNo text not null,locationCode text not null,receiptCode text not null,serverDbName text not null,printerMac text not null,repareacode text not null,repdealcode text not null,reproutecode text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_AREA
					+ "(farea_id integer primary key autoincrement,AreaCode text not null,AreaName text not null,RegCode text not null,DealCode text not null,AddUser text not null,AddDatefarea text not null,AddMach text not null,RecordId text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_LOCATION
					+ "(flocation_id integer primary key autoincrement,AddMach text not null,AddUser text not null,Address1 text not null,Address2 text not null,Address3 text not null,Contact text not null,EMail text not null,FaxNo text not null,LocCode text not null,LocName text not null,LoctCode text not null,RecordId text not null,RepCode text not null,TeleNo text not null,LocAddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEMS
					+ "(_id integer primary key autoincrement,SKUCode text not null,ItemCode text not null,MapCode text not null,ItemName text not null,VenPcode text not null,GroupCode text not null,TypeCode text not null,TaxComCode text not null,UnitCode text not null,SkuSizCode text not null,ItemStatus text not null,ReOrderLvl text not null,ReOrderQty text not null,AvgPrice text not null,PurAcc text not null,PurRetAcc text not null,SVATAcc text not null,ExportAcc text not null,IndrExAcc text not null,SalAcc text not null,SalRetAcc text not null,DisAcc text not null,ClsStkAcc text not null,StkInAcc text not null,PrilCode text not null,BrandCode text not null,SBrandCode text not null,NOUCase text not null,OrdSeq text not null,AddUser text not null,AddDatefitem text not null,AddMach text not null,RecordId text not null,timestamp_column text not null,MustSale  text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_PRICE
					+ "(fitempri_id integer primary key autoincrement,SKUCode text not null,ItemCode text not null,PrilCode text not null,PriRDate text not null,Price text not null,AddUser text not null,AddDateIP text not null,AddMach text not null,Txnuser text not null,TxnDate text not null,TxnMach text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_LOC_DETAILS
					+ "(flocdet_id integer primary key autoincrement,LocCode text not null,ItemCode text not null,QOH text not null,RecordId text not null,timestamp_column text not null,syncRec text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_DEBTOR
					+ "(_id integer primary key autoincrement,DebCode text not null,DebName text not null,DebAdd1 text not null,DebAdd2 text not null,DebAdd3 text not null,DebTele text not null,DebMob text not null,DebEMail text not null,CretDate text not null,OutDis text not null,RemDis text not null,TownCode text not null,AreaCode text not null,DebCatCode text not null,DbGrCode text not null,DebClsCode text not null,Status text not null,DebLylty text not null,DealCode text not null,AddUser text not null,AddDateDEB text not null,AddMach text not null,RecordId text not null,timestamp_column text not null,CrdPeriod text not null,ChkCrdPrd text not null,CrdLimit text not null,ChkCrdLmt text not null,RepCode text not null,RankCode text not null,txndate text not null,TranBatch text not null,DebSumary text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_CONTROL
					+ "(fcontrol_id integer primary key autoincrement,ComName text not null,ComAdd1 text not null,ComAdd2 text not null,ComAdd3 text not null,comtel1 text not null,comtel2 text not null,comfax1 text not null,comemail text not null,comweb text not null,confyear text not null,contyear text not null,comRegNo text not null,ConfTxn text not null,ContTxn text not null,Crystalpath text not null,VatCmTaxNo text not null,NbtCmTaxNo text not null,SysId text not null,DealCode text not null,basecur text not null,BalgCrLm text not null,conage1 text not null,conage2 text not null,conage3 text not null,conage4 text not null,conage5 text not null,conage6 text not null,conage7 text not null,conage8 text not null,conage9 text not null,conage10 text not null,conage11 text not null,conage12 text not null,conage13 text not null,conage14 text not null);");

			mydb.execSQL("create table if not exists "
					+ ITEM_COMPANY_SETTING
					+ "(fcomset_id integer primary key autoincrement,cSettingsCode text not null,cSettingGrp text not null,cLocationChar text not null,cCharVal text not null,nNumVal text not null,cRemarks text not null,nType text not null,bUpdateFlag text not null,cCompanyCode text not null,recordid text not null,timestamp_column text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_REP_ROUTE
					+ "(route_id integer primary key autoincrement,RepCode text not null,RouteCode text not null,RouteName text not null,RecordId text not null,AddDate text not null,AreaCode text not null,DealCode text not null,FreqNo text not null,Km text not null,MinProcall text not null,RDAloRate text not null,RDTarget text not null,Remarks text not null,Status text not null,Tonnage text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_REP_ROUTEDET
					+ "(fRouteDet_id integer primary key autoincrement,RecordId text not null,DebCode text not null,RouteCode text not null);");

			mydb.execSQL("create table if not exists "
					+ BANK_DETAILS
					+ "(bankre_id integer primary key autoincrement,RecordId text not null,bankcode text not null,bankname text not null,bankaccno text not null,Branch text not null,bankadd1 text not null,bankadd2 text not null,AddDate text not null);");

			mydb.execSQL("create table if not exists "
					+ SALES_ORD_REASON
					+ "(freason_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,ReaCode text not null,ReaName text not null,ReaTcode text not null,RecordId text not null,Type text not null);");

			mydb.execSQL("create table if not exists "
					+ USER_EXPENSE
					+ "(uexp_id integer primary key autoincrement,ExpCode text not null,ExpGrpCode text not null,ExpName text not null,RecordId text not null,Status text not null,AddMach text not null,AddUser text not null);");

			mydb.execSQL("create table if not exists "
					+ TOWN_DETAILS
					+ "(townre_id integer primary key autoincrement,RecordId text not null,TownCode text not null,TownName text not null,DistrCode text not null,AddDate text not null,AddMach text not null,AddUser text not null);");

			mydb.execSQL("create table if not exists "
					+ MERCH_DETAILS
					+ "(merchre_id integer primary key autoincrement,RecordId text not null,MerchCode text not null,MerchName text not null,AddUser text not null,AddMach text not null,AddDate text not null);");

			// New Master Tables
			mydb.execSQL("create table if not exists "
					+ FTRGCAPUL
					+ "(ftrg_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,DealCode text not null,Month text not null,Qty text not null,RecordId text not null,RepCode text not null,SKUCode text not null,Year text not null);");

			mydb.execSQL("create table if not exists "
					+ FTYPE
					+ "(ftype_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,RecordId text not null,TypeCode text not null,TypeName text not null);");

			mydb.execSQL("create table if not exists "
					+ FSUBBRAND
					+ "(fsubbrand_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,RecordId text not null,SBrandCode text not null,SBrandName text not null);");

			mydb.execSQL("create table if not exists "
					+ FGROUP
					+ "(fgroup_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,GroupCode text not null,GroupName text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ FSKU
					+ "(fsku_id integer primary key autoincrement,AddDate text not null,AddMach text not null,AddUser text not null,BrandCode text not null,GroupCode text not null,ItemStatus text not null,MustSale text not null,NOUCase text not null,OrdSeq text not null,RecordId text not null,SBrandCode text not null,SKUCode text not null,SkuName text not null,SkuSizCode text not null,Tonnage text not null,TypeCode text not null,Unit text not null);");

			mydb.execSQL("create table if not exists "
					+ FBRAND
					+ "(fbrand_id integer primary key autoincrement,AddMach text not null,AddUser text not null,BrandCode text not null,BrandName text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_COMPANY_BRANCH
					+ "(fcombra_id integer primary key autoincrement,BranchCode text not null,RecordId text not null,cSettingsCode text not null,nNumVal text not null);");

			mydb.execSQL("create table if not exists "
					+ INV_SAL_REP
					+ "(fsalrep_id integer primary key autoincrement,ASECode text not null,AreaCode text not null,DealCode text not null,RecordId text not null,RepCode text not null,RepPrefix text not null,RepTCode text not null);");

		} catch (Exception e) {
		}
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);
					UserLocCode = selectCurrentuserrec.getString(5);
					serverDbName = selectCurrentuserrec.getString(7);
					RepRouteCode = selectCurrentuserrec.getString(11);
				}
			}
		}

		selectCurrentuserrec.close();
		mydb.close();
	}

	private void checkCurrentServerDB() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectServerDB = null;
		try {
			selectServerDB = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (selectServerDB != null) {
			if (selectServerDB.getCount() > 0) {
				while (selectServerDB.moveToNext()) {
					currentUserServerDB = selectServerDB.getString(7);
				}
			}
		}
		selectServerDB.close();
		mydb.close();
	}

	protected void agentPrefixSalesOrder() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					AgentPrefixType = selectAgentPreType.getString(18);
					AgentDealCode = selectAgentPreType.getString(19);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	// ******Uploading Details Using New Rallback Web Service******
		private class UploadingInvoiceDataValuesTesting extends
				AsyncTask<Void, Void, Void> {
			private final String TAG = null;

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// Create a progressdialog
				mProgressDialog = new ProgressDialog(DM_Application_Manage_Tools.this);
				mProgressDialog.setMax(100);
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				mProgressDialog.setCancelable(false);
				// Set progressdialog title
				mProgressDialog.setTitle("Uploading");
				// Set progressdialog message
				mProgressDialog.setMessage("Uploading Invoice Details...");
				mProgressDialog.setIndeterminate(false);
				// Show progressdialog
				mProgressDialog.show();
			}

			@Override
			protected Void doInBackground(Void... arg0) {
				// TODO Auto-generated method stub
				mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
				Cursor selectFcompanyBranch = null;
				// Secondry Invoice Cursors
				Cursor selectInvHeadDetails = null;
				Cursor selectInvDetailsData = null;
				// Sales Order Invoice Cursors
				Cursor selectOrderHeader = null;
				Cursor selectOrderDetails = null;
				// Secondry invoice Cancel Details
				Cursor selectSIcancelHedDetDetails = null;
				Cursor selectSOcancelHedDetDetails = null;

				// Unloading Records Details
				Cursor selectStockUnloadHeader = null;
				Cursor selectStockUnLoadDetails = null;

				// company branch
				try {
					selectFcompanyBranch = mydb.query(INV_COMPANY_BRANCH, null,
							null, null, null, null, null);
				} catch (Exception e) {
				}
				// *******Secondry Invoice********
				try {
					selectInvHeadDetails = mydb.query(INV_HEADER, null,
							"invhedSync ='0'", null, null, null, null);
				} catch (Exception e) {
				}
				try {
					selectInvDetailsData = mydb.query(INV_DETAILS, null,
							"invdetSync ='0'", null, null, null, null);
				} catch (Exception e) {
				}
				// *******Sales Orders Invoice********
				try {
					selectOrderHeader = mydb.query(STOCK_ORDER_HEAD, null,
							"stordhedSync ='0'", null, null, null, null);
				} catch (Exception e) {
				}
				try {
					selectOrderDetails = mydb.query(STOCK_ORDER_DETAIL, null,
							"storddetSync ='0'", null, null, null, null);
				} catch (Exception e) {
				}

				
				// ******Upload fCompanyBranch**************
				//checkNetworkUploading();
				if (selectFcompanyBranch != null) {
					if (selectFcompanyBranch.getCount() > 0) {
						while (selectFcompanyBranch.moveToNext()) {
							String BranchCode = selectFcompanyBranch.getString(1);
							String RecordId = selectFcompanyBranch.getString(2);
							String cSettingsCode = selectFcompanyBranch
									.getString(3);

							if (cSettingsCode.equals("SECINV")
									|| cSettingsCode.equals("SECORD")) {

								String nNumVal = selectFcompanyBranch.getString(4);
								HttpPost request = new HttpPost(
										connectionURL
												+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/InUpdatefCompanyBranch");

								JSONStringer userJson = null;

								try {

									userJson = new JSONStringer().object()
											.key("fCBInUp").object()
											.key("BranchCode").value(BranchCode)
											.key("cSettingsCode")
											.value(cSettingsCode).key("nNumVal")
											.value(nNumVal).key("DbName")
											.value(currentUserServerDB).endObject();
									// .key("RecordId").value("10")
									Log.e("json", "json created");
								} catch (JSONException e) {

									// TODO Auto-generated catch block
									e.printStackTrace();
								}

								StringEntity entity = null;
								try {
									entity = new StringEntity(userJson.toString(),
											"UTF-8");
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								entity.setContentEncoding(new BasicHeader(
										HTTP.CONTENT_TYPE, "application/json"));
								entity.setContentType("application/json");

								request.setEntity(entity);
								Log.e("Request xxx", "Request xxx:" + userJson);
								// Send request to WCF service
								DefaultHttpClient httpClient = new DefaultHttpClient();

								try {
									Log.e("response", "connect");
									HttpResponse response = httpClient
											.execute(request);
									// ===========================================================
									HttpEntity entitye = response.getEntity();
									is = entity.getContent();
									if (is != null) {

										try {
											BufferedReader reader = new BufferedReader(
													new InputStreamReader(is,
															"iso-8859-1"), 8);
											sb = new StringBuilder();
											sb.append(reader.readLine() + "\n");
											String line = "0";
											while ((line = reader.readLine()) != null) {
												sb.append(line + "\n");
											}
											is.close();
											String result = sb.toString();
											Log.e("String Responce",
													"Print Responce xxx:" + result);
										} catch (Exception e1) {
											e1.printStackTrace();
										}
									}
									// ==================================
									Log.e("response",
											"response get:" + response.toString());
									// System.out.println(response.toString());
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(response
													.getEntity().getContent(),
													"UTF-8"));
									String json = reader.readLine();
									Log.e("json string", "test " + json.toString()
											+ " lazım");
									System.out.println(json);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}

						}
						arrayLength = 7;
						progressHandler
								.sendMessage(progressHandler.obtainMessage());
					}

				}

				// *******Secondry Invoice Uploading Start********
				// ******Upload FInvHed**************
				//checkNetworkUploading();
				// int fInvHedCount = 0 , fOrdHedCount = 0;
				fInvHedCount = selectInvHeadDetails.getCount();
				if (selectInvHeadDetails != null) {
					if (selectInvHeadDetails.getCount() > 0) {
						while (selectInvHeadDetails.moveToNext()) {
							String RefNo = selectInvHeadDetails.getString(1);
							String RefNo1 = selectInvHeadDetails.getString(2);
							String InvType = selectInvHeadDetails.getString(3);
							String TxnDate = selectInvHeadDetails.getString(4);
							try {
								date = originalFormat.parse(TxnDate.replaceAll(
										"[-+/.^:,]", " "));
								TxnDate = targetFormat.format(date);
							} catch (ParseException ex) {
								TxnDate = "1900-01-01";
							}
							String ManuRef = selectInvHeadDetails.getString(5);
							String DealCode = selectInvHeadDetails.getString(6);
							String RepCode = selectInvHeadDetails.getString(7);
							String AreaCode = selectInvHeadDetails.getString(8);
							String RouteCode = selectInvHeadDetails.getString(9);
							String DebCode = selectInvHeadDetails.getString(10);
							String LocCode = selectInvHeadDetails.getString(11);
							String Remarks = selectInvHeadDetails.getString(12);
							String CostCode = selectInvHeadDetails.getString(13);
							String CurCode = selectInvHeadDetails.getString(14);
							String CurRate = selectInvHeadDetails.getString(15);
							String TxnType = selectInvHeadDetails.getString(16);
							String InvAmt = selectInvHeadDetails.getString(17);
							String OutDis = selectInvHeadDetails.getString(18);
							// Invoice Discount Value
							String InvDis = selectInvHeadDetails.getString(19);
							double InvDisVal = Double.parseDouble(InvDis
									.replaceAll("[,]", ""));
							String TotMkrAmt = selectInvHeadDetails.getString(20);
							String UnOvAmt = selectInvHeadDetails.getString(21);
							// Total Discount
							String TotalDis = selectInvHeadDetails.getString(22);
							double TotalDisVal = Double.parseDouble(TotalDis
									.replaceAll("[,]", ""));
							String TotalAmt = selectInvHeadDetails.getString(23);
							double TotalAmtdou = Double.parseDouble(TotalAmt
									.replaceAll("[,]", ""));
							double FTotalAmt = TotalAmtdou + 0.00;
							String PrintFTotalAmt = Double.toString(FTotalAmt);
							String AddUser = selectInvHeadDetails.getString(24);
							String AddDate = selectInvHeadDetails.getString(25);
							String AddMach = selectInvHeadDetails.getString(26);
							String prtcopy = selectInvHeadDetails.getString(27);
							String TranBatch = selectInvHeadDetails.getString(30);
							// Header Discount
							String outDisVal = selectInvHeadDetails.getString(33);
							double outDisValue = Double.parseDouble(outDisVal
									.replaceAll("[,]", ""));
							// Line Items Discount
							double LineItemsDis = TotalDisVal
									- (InvDisVal + outDisValue);
							String LineItemsDisString = Double
									.toString(LineItemsDis);
							// Create values JSONArray
							JSONArray valuesarrayFinvHed = new JSONArray();

							try {
								// Create values jsonObject
								JSONObject valuesJsonFinvHed = new JSONObject();
								valuesJsonFinvHed.put("RefNo", RefNo);
								valuesJsonFinvHed.put("RefNo1", RefNo1);
								valuesJsonFinvHed.put("InvType", InvType);
								valuesJsonFinvHed.put("TxnDate", TxnDate);
								valuesJsonFinvHed.put("ManuRef", ManuRef);
								valuesJsonFinvHed.put("DealCode", DealCode);
								valuesJsonFinvHed.put("RepCode", RepCode);
								valuesJsonFinvHed.put("AreaCode", AreaCode);
								valuesJsonFinvHed.put("RouteCode", RouteCode);
								valuesJsonFinvHed.put("DebCode", DebCode);
								valuesJsonFinvHed.put("LocCode", LocCode);
								valuesJsonFinvHed.put("Remarks", Remarks);
								valuesJsonFinvHed.put("CostCode", CostCode);
								valuesJsonFinvHed.put("CurCode", CurCode);
								valuesJsonFinvHed.put("CurRate", CurRate);
								valuesJsonFinvHed.put("TxnType", TxnType);
								valuesJsonFinvHed.put("InvAmt", InvAmt);
								valuesJsonFinvHed.put("OutDis", OutDis);
								valuesJsonFinvHed.put("InvDis", InvDis);
								valuesJsonFinvHed.put("TotMkrAmt",
										TotMkrAmt.replaceAll("[,]", ""));
								valuesJsonFinvHed.put("UnOvAmt",
										UnOvAmt.replaceAll("[,]", ""));
								valuesJsonFinvHed.put("TotalDis",
										TotalDis.replaceAll("[,]", ""));
								valuesJsonFinvHed.put("TotalItmDis",
										LineItemsDisString.replaceAll("[,]", ""));
								valuesJsonFinvHed.put("TotalAmt",
										PrintFTotalAmt.replaceAll("[,]", ""));
								valuesJsonFinvHed.put("AddUser", AddUser);
								valuesJsonFinvHed.put("AddDate", AddDate);
								valuesJsonFinvHed.put("AddMach", AddMach);
								valuesJsonFinvHed.put("prtcopy", prtcopy);
								valuesJsonFinvHed.put("outDisVal", outDisVal);
								valuesJsonFinvHed.put("TranBatch", " ");
								valuesJsonFinvHed
										.put("DbName", currentUserServerDB);

								valuesarrayFinvHed.put(valuesJsonFinvHed
										.remove("[,]"));
								arFinvHed.add(valuesJsonFinvHed.toString());
							} catch (Exception ex) {
								ex.printStackTrace();
							}
						}
						arrayLength = 7;
						progressHandler
								.sendMessage(progressHandler.obtainMessage());
					}
				}
				//checkNetworkUploading();
				if (selectInvDetailsData != null) {
					if (selectInvDetailsData.getCount() > 0) {
						while (selectInvDetailsData.moveToNext()) {
							String RefNo = selectInvDetailsData.getString(1);
							String TxnDate = selectInvDetailsData.getString(2);
							try {
								date = originalFormat.parse(TxnDate.replaceAll(
										"[-+/.^:,]", " "));
								TxnDate = targetFormat.format(date);

							} catch (ParseException ex) {
								TxnDate = "1900-01-01";
							}
							String TxnType = selectInvDetailsData.getString(3);
							String SeqNo = selectInvDetailsData.getString(4);
							String Itemcode = selectInvDetailsData.getString(5);
							String Txnseqno = selectInvDetailsData.getString(6);
							String SellPrice = selectInvDetailsData.getString(7);
							String BSellPrice = selectInvDetailsData.getString(8);
							String TSellPrice = selectInvDetailsData.getString(9);
							String BTSellPrice = selectInvDetailsData.getString(10);
							String CostPrice = selectInvDetailsData.getString(11);
							String CaseQty = selectInvDetailsData.getString(12);
							String Type = selectInvDetailsData.getString(13);
							String PiceQty = selectInvDetailsData.getString(14);
							String Qty = selectInvDetailsData.getString(15);
							String BalQty = selectInvDetailsData.getString(16);
							String DisPer = selectInvDetailsData.getString(17);
							String DisAmt = selectInvDetailsData.getString(18);
							String BDisAmt = selectInvDetailsData.getString(19);
							String TaxAmt = selectInvDetailsData.getString(20);
							String BTaxAmt = selectInvDetailsData.getString(21);
							String Amt = selectInvDetailsData.getString(22);
							String BAmt = selectInvDetailsData.getString(23);
							String ReaCode = selectInvDetailsData.getString(24);
							String Linkrec = selectInvDetailsData.getString(25);
							String RecordId = selectInvDetailsData.getString(26);
							String itemDescription = selectInvDetailsData
									.getString(27);
							String refInvoiceDetNo = selectInvDetailsData
									.getString(28);
							String refInvoiceDetCode = selectInvDetailsData
									.getString(29);
							String refInvitemCaseQty = selectInvDetailsData
									.getString(30);
							String invDetAddDate = selectInvDetailsData
									.getString(33);
							String itemdisper = selectInvDetailsData.getString(34);
							String itemdisperval = selectInvDetailsData
									.getString(35);
							double totlineItemDis = Double.parseDouble(BDisAmt
									.replaceAll("[,]", ""));
							double DisPerAmount = Double.parseDouble(itemdisperval
									.replaceAll("[,]", ""));
							double DisValueAmtCal = totlineItemDis - DisPerAmount;
							String DisValueAmtCalStr = Double
									.toString(DisValueAmtCal);
							String reasonCode = selectInvDetailsData.getString(36);

							// Create values JSONArray
							JSONArray valuesarrayFinvDet = new JSONArray();

							try {
								checkrall = checkrall + 1;
								// Create values jsonObject
								JSONObject valuesJsonFinvDet = new JSONObject();
								valuesJsonFinvDet.put("RefNo", refInvoiceDetCode);
								valuesJsonFinvDet.put("TxnDate", TxnDate);
								valuesJsonFinvDet.put("TxnType", TxnType);
								valuesJsonFinvDet.put("SeqNo", SeqNo);
								valuesJsonFinvDet.put("Itemcode", Itemcode);
								valuesJsonFinvDet.put("Txnseqno", Txnseqno);
								valuesJsonFinvDet.put("SellPrice",
										SellPrice.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("SellPrice",
										SellPrice.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("BSellPrice",
										BSellPrice.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("TSellPrice",
										TSellPrice.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("BTSellPrice",
										BTSellPrice.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("CostPrice",
										CostPrice.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("CaseQty",
										CaseQty.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("PiceQty",
										PiceQty.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("Type", Type);
								valuesJsonFinvDet.put("Qty",
										Qty.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("BalQty",
										BalQty.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("DisPer",
										DisPer.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("DisAmt",
										DisAmt.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("BDisAmt",
										BDisAmt.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("TaxAmt",
										TaxAmt.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("BTaxAmt",
										BTaxAmt.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("Amt",
										Amt.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("BAmt",
										BAmt.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("ReaCode", ReaCode);
								valuesJsonFinvDet.put("Linkrec", "0");
								valuesJsonFinvDet.put("DisPerAmt",
										itemdisperval.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("DisValAmt",
										DisValueAmtCalStr.replaceAll("[,]", ""));
								valuesJsonFinvDet.put("LocCode", UserLocCode);
								valuesJsonFinvDet
										.put("DbName", currentUserServerDB);
								valuesarrayFinvDet.put(valuesJsonFinvDet
										.remove("[,]"));
								arFinvDet.add(valuesJsonFinvDet.toString());

							} catch (Exception e) {
							}
						}
						arrayLength = 7;
						progressHandler
								.sendMessage(progressHandler.obtainMessage());
					}
				}
				//checkNetworkUploading();
				String strFH = arFinvHed.toString();
				String strFD = arFinvDet.toString();

				if (selectInvHeadDetails.getCount() <= 0) {
					Log.v(TAG, "ARRAY 1" + strFH + "/" + strFD);
				} else {
					strFH = strFH.replace("[", "");
					strFH = strFH.replace("]", "");
					strFD = strFD.replace("[", "");
					strFD = strFD.replace("]", "");
					// PDADBWebServiceM
					HttpPost request = new HttpPost(
							connectionURL
									+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/insertFInvHed");
					JSONStringer userJson = null;
					try {
						userJson = new JSONStringer().object().key("fHed")
								.value(strFH).key("fDet").value(strFD);
					} catch (Exception e) {
					}

					StringEntity entity = null;
					try {
						// String repval = userJson.toString() + "}" + ",UTF-8";
						String format1 = userJson.toString().replace("[", "");
						String format2 = format1.replace("]", "");
						String format3 = format2.replace("\\", "");

						String format4 = "\"fHed\":\"";
						// String ggg = ",\"fDet\":\"";
						String format5 = "\",\"fDet\":\"";

						String format6 = format3.replace(format4, "\"fHed\":[");
						String format7 = format6.replace(format5, "],\"fDet\":[");
						format7 = format7 + "}";
						String dj = format7.replace("\"}\"}", "\"}]}");

						/*
						 * Log.v(TAG, "****************************************\n");
						 * Log.v(TAG, "JSON1 =" + dj);
						 */
						entity = new StringEntity(dj, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
							"application/json"));
					entity.setContentType("application/json");
					request.setEntity(entity);

					// Send request to WCF service
					DefaultHttpClient httpClient = new DefaultHttpClient();

					try {
						Log.e("response", "connect");
						HttpResponse response = httpClient.execute(request);
						// Log.e("RES DJ1:", "RES DJ1:" + response.toString());
						// ===========================================================
						HttpEntity entitye = response.getEntity();
						is = entitye.getContent();
						if (is != null) {
							int resval = 200;
							try {
								BufferedReader reader = new BufferedReader(
										new InputStreamReader(is, "iso-8859-1"), 8);
								sb = new StringBuilder();
								sb.append(reader.readLine() + "\n");
								String line = "0";
								while ((line = reader.readLine()) != null) {
									sb.append(line + "\n");
								}
								is.close();
								String result = sb.toString();
								Log.v(TAG, "CHKQUERY: =" + result);
								String result1 = result.replace("\"", "");
								// int result1Val =
								// Integer.parseInt(result1.trim());

								if (result1.trim().equals("200")) {
									Log.e("RES DJ3:", "RESULT 200 P1:" + result1);
									ContentValues finvhedSynUpdateVal = new ContentValues();
									finvhedSynUpdateVal.put("invhedSync", "1");
									mydb.update(INV_HEADER, finvhedSynUpdateVal,
											"invhedSync ='0'", null);
									ContentValues finvdetSynUpdateVal = new ContentValues();
									finvdetSynUpdateVal.put("invdetSync", "1");
									mydb.update(INV_DETAILS, finvdetSynUpdateVal,
											"invdetSync ='0'", null);
									String fInvHedCountStr = Integer
											.toString(fInvHedCount);
									SIupSummary = "(SI -" + fInvHedCountStr + "/"
											+ fInvHedCountStr + ")";
								}

								else {
									String result12 = result.replace("\",", "");
									String result13 = result12.replace("\"", "");
									String result14 = result13.replace("\\", "");
									String result15 = result14.replace("200,", "");
									String[] items = result15.split(",");
									List<String> container = Arrays.asList(items);
									List<String> android = new ArrayList<String>(
											container);
									Log.e("RES DJ2:", "RESULT ELSE 200 :" + android);
									// Getting Iterator from List
									Iterator<String> iteratorSI = android
											.iterator();
									try {
										selectInvHeadDetailsReChk = mydb.query(
												INV_HEADER, null,
												"invhedSync ='0'", null, null,
												null, null);
									} catch (Exception e) {
									}
									try {
										selectInvDetailsDataReChk = mydb.query(
												INV_DETAILS, null,
												"invdetSync ='0'", null, null,
												null, null);
									} catch (Exception e) {
									}
									int i = 1;
									while (iteratorSI.hasNext()) {

										ReadRefErrorUpload = iteratorSI.next();

										try {
											Log.e("RES DJ2:", "SYNC FAIL HED 7 :"
													+ ReadRefErrorUpload);
											selectInvHeadDetailsReChk = mydb.query(
													INV_HEADER,
													null,
													"RefNo ='"
															+ ReadRefErrorUpload
																	.trim() + "'",
													null, null, null, null);
										} catch (Exception e) {
										}
										try {
											Log.e("RES DJ2:", "SYNC FAIL DET 7 :"
													+ ReadRefErrorUpload);
											selectInvDetailsDataReChk = mydb.query(
													INV_DETAILS,
													null,
													"RefNo ='"
															+ ReadRefErrorUpload
																	.trim() + "'",
													null, null, null, null);
										} catch (Exception e) {
										}

										Log.e("RES DJ2:",
												"CHK HED:"
														+ selectInvHeadDetailsReChk
																.getCount() + " = "
														+ i);
										Log.e("RES DJ2:",
												"CHK DET:"
														+ selectInvDetailsDataReChk
																.getCount() + " = "
														+ i);

										if (selectInvHeadDetailsReChk != null) {
											if (selectInvHeadDetailsReChk
													.getCount() > 0) {
												while (selectInvHeadDetailsReChk
														.moveToNext()) {
													String syncUpdateHedSI = selectInvHeadDetailsReChk
															.getString(1);
													ContentValues finvHedSynUpdaterall = new ContentValues();
													Log.e("RES DJ2:",
															"SYNC FAIL 7 UPDATE HED:"
																	+ syncUpdateHedSI);
													finvHedSynUpdaterall.put(
															"invhedSync", "7");
													mydb.update(
															INV_HEADER,
															finvHedSynUpdaterall,
															"RefNo ='"
																	+ syncUpdateHedSI
																	+ "'", null);
												}
											}
											// selectInvHeadDetailsReChk.close();
										}

										if (selectInvDetailsDataReChk != null) {
											if (selectInvDetailsDataReChk
													.getCount() > 0) {
												while (selectInvDetailsDataReChk
														.moveToNext()) {
													String syncUpdateDetSI = selectInvDetailsDataReChk
															.getString(1);
													ContentValues finvdetSynUpdaterall = new ContentValues();
													Log.e("RES DJ2:",
															"SYNC FAIL 7 UPDATE DET:"
																	+ syncUpdateDetSI);
													finvdetSynUpdaterall.put(
															"invdetSync", "7");
													mydb.update(
															INV_DETAILS,
															finvdetSynUpdaterall,
															"RefNo ='"
																	+ syncUpdateDetSI
																	+ "'", null);
												}
											}
											// selectInvHeadDetailsReChk.close();
										}
										i = i + 1;
										fInvHedCountFail = fInvHedCountFail + 1;
										String fInvHedCountStr = Integer
												.toString(fInvHedCount);
										String fInvHedCountStrFail = Integer
												.toString(fInvHedCountFail);
										SIupSummary = "(SI -" + fInvHedCountStrFail
												+ "/" + fInvHedCountStr + ")";
										// iteratorSI.next();
									}

									iteratorSI.remove();
									try {
										selectInvHeadDetailsUpdate = mydb.query(
												INV_HEADER, null,
												"invhedSync ='0'", null, null,
												null, null);
									} catch (Exception e) {
									}
									try {
										selectInvDetailsDataUpdate = mydb.query(
												INV_DETAILS, null,
												"invdetSync ='0'", null, null,
												null, null);
									} catch (Exception e) {
									}

									if (selectInvHeadDetailsUpdate != null) {
										if (selectInvHeadDetailsUpdate.getCount() > 0) {
											while (selectInvHeadDetailsUpdate
													.moveToNext()) {
												String mainRefNoHed = selectInvHeadDetailsUpdate
														.getString(1);
												Log.e("RES DJ2:", "SYNC OK HED :"
														+ mainRefNoHed);
												ContentValues finvhedSynUpdaterall = new ContentValues();
												finvhedSynUpdaterall.put(
														"invhedSync", "1");
												mydb.update(INV_HEADER,
														finvhedSynUpdaterall,
														"RefNo ='" + mainRefNoHed
																+ "'", null);
											}
										}
									}
									if (selectInvDetailsDataUpdate != null) {
										if (selectInvDetailsDataUpdate.getCount() > 0) {
											while (selectInvDetailsDataUpdate
													.moveToNext()) {
												String mainRefNoDet = selectInvDetailsDataUpdate
														.getString(1);
												Log.e("RES DJ2:", "SYNC OK DET :"
														+ mainRefNoDet);
												ContentValues finvdetSynUpdaterall = new ContentValues();
												finvdetSynUpdaterall.put(
														"invdetSync", "1");
												mydb.update(INV_DETAILS,
														finvdetSynUpdaterall,
														"RefNo ='" + mainRefNoDet
																+ "'", null);
											}
										}
									}

									try {
										selectInvHeadDetailsChkFail = mydb.query(
												INV_HEADER, null,
												"invhedSync ='7'", null, null,
												null, null);
									} catch (Exception e) {
									}
									try {
										selectInvDetailsDataChkFail = mydb.query(
												INV_DETAILS, null,
												"invdetSync ='7'", null, null,
												null, null);
									} catch (Exception e) {
									}

									if (selectInvHeadDetailsChkFail != null) {
										if (selectInvHeadDetailsChkFail.getCount() > 0) {
											while (selectInvHeadDetailsChkFail
													.moveToNext()) {

												String mainRefNoHedFail = selectInvHeadDetailsChkFail
														.getString(1);
												Log.e("RES DJ2:",
														"SYNC FAIL UPDATE HED :"
																+ mainRefNoHedFail);
												ContentValues finvhedSynUpdaterallFail = new ContentValues();
												finvhedSynUpdaterallFail.put(
														"invhedSync", "0");
												mydb.update(INV_HEADER,
														finvhedSynUpdaterallFail,
														"RefNo ='"
																+ mainRefNoHedFail
																+ "'", null);
											}
										}
									}
									if (selectInvDetailsDataChkFail != null) {
										if (selectInvDetailsDataChkFail.getCount() > 0) {
											while (selectInvDetailsDataChkFail
													.moveToNext()) {
												String mainRefNoDetFail = selectInvDetailsDataChkFail
														.getString(1);
												Log.e("RES DJ2:",
														"SYNC FAIL UPDATE DET :"
																+ mainRefNoDetFail);
												ContentValues finvdetSynUpdaterallFail = new ContentValues();
												finvdetSynUpdaterallFail.put(
														"invdetSync", "0");
												mydb.update(INV_DETAILS,
														finvdetSynUpdaterallFail,
														"RefNo ='"
																+ mainRefNoDetFail
																+ "'", null);
											}
										}
									}
								}

							} catch (Exception e1) {
								e1.printStackTrace();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					arFinvHed.clear();
					arFinvDet.clear();

				}

				// *******Sales Order Invoice Uploading Start********
				//checkNetworkUploading();
				fOrdHedCount = selectOrderHeader.getCount();
				if (selectOrderHeader != null) {
					if (selectOrderHeader.getCount() > 0) {
						while (selectOrderHeader.moveToNext()) {
							// FStoOrdersHedIndex = selectOrderHeader.getString(0);
							String AddMach = selectOrderHeader.getString(1);
							String AddUser = selectOrderHeader.getString(2);
							String AreaCode = selectOrderHeader.getString(3);
							String CostCode = selectOrderHeader.getString(4);
							String CurCode = selectOrderHeader.getString(5);
							String CurRate = selectOrderHeader.getString(6);
							String DealCode = selectOrderHeader.getString(7);
							String DebCode = selectOrderHeader.getString(8);
							String InvAmt = selectOrderHeader.getString(9);
							String InvDis = selectOrderHeader.getString(10);
							double InvDisVal = Double.parseDouble(InvDis
									.replaceAll("[,]", ""));
							String InvFlg = selectOrderHeader.getString(11);
							String LocCode = selectOrderHeader.getString(12);
							String ManuRef = selectOrderHeader.getString(13);
							String OutDis = selectOrderHeader.getString(14);
							String RecordId = selectOrderHeader.getString(15);
							String RefNo = selectOrderHeader.getString(16);
							String Remarks = selectOrderHeader.getString(17);
							String RepCode = selectOrderHeader.getString(18);
							String RouteCode = selectOrderHeader.getString(19);
							String TotMkrAmt = selectOrderHeader.getString(20);
							String TotalAmt = selectOrderHeader.getString(21);
							String TotalDis = selectOrderHeader.getString(22);
							double TotalDisVal = Double.parseDouble(TotalDis
									.replaceAll("[,]", ""));
							String TranBatch = selectOrderHeader.getString(23);
							String TxnType = selectOrderHeader.getString(24);
							String UnOvAmt = selectOrderHeader.getString(25);
							String prtcopy = selectOrderHeader.getString(26);
							String TxnDate = selectOrderHeader.getString(27);
							String outDisVal = selectOrderHeader.getString(30);
							UploadodAddDate = selectOrderHeader.getString(31);
							String DeliverAddDate = selectOrderHeader.getString(32);

							try {
								date = originalFormat.parse(DeliverAddDate
										.replaceAll("[-+/.^:,]", " "));
								DeliverAddDate = targetFormat.format(date);

							} catch (ParseException ex) {
							}

							// Log.v(TAG, "DDDD :" + UploadodAddDate);
							try {
								if (UploadodAddDate.equals(null)) {
									UploadodAddDate = getAddDateTimeString()
											.toString();
								}
							} catch (Exception ex) {
								UploadodAddDate = getAddDateTimeString().toString();
							}
							double outDisValue = Double.parseDouble(outDisVal
									.replaceAll("[,]", ""));
							// Line Items Discount
							double LineItemsDis = TotalDisVal
									- (InvDisVal + outDisValue);
							String LineItemsDisString = Double
									.toString(LineItemsDis);

							try {
								date = originalFormat.parse(TxnDate.replaceAll(
										"[-+/.^:,]", " "));
								TxnDate = targetFormat.format(date);

							} catch (ParseException ex) {
								TxnDate = "1900-01-01";
							}

							// Create values JSONArray
							JSONArray valuesarrayFordHed = new JSONArray();
							try {
								// Create values jsonObject
								JSONObject valuesJsonFOrdHed = new JSONObject();
								valuesJsonFOrdHed.put("RefNo", RefNo);
								valuesJsonFOrdHed.put("TxnDate", TxnDate);
								valuesJsonFOrdHed.put("ManuRef", ManuRef);
								valuesJsonFOrdHed.put("DelvDate", DeliverAddDate);
								valuesJsonFOrdHed.put("DealCode", AgentDealCode);
								valuesJsonFOrdHed.put("RepCode", RepCode);
								valuesJsonFOrdHed.put("AreaCode", AreaCode);
								valuesJsonFOrdHed.put("RouteCode", RepRouteCode);
								valuesJsonFOrdHed.put("DebCode", DebCode);
								valuesJsonFOrdHed.put("LocCode", LocCode);
								valuesJsonFOrdHed.put("Remarks", Remarks);
								valuesJsonFOrdHed.put("CostCode", CostCode);
								valuesJsonFOrdHed.put("CurCode", CurCode);
								valuesJsonFOrdHed.put("CurRate", CurRate);
								valuesJsonFOrdHed.put("TxnType", TxnType);
								valuesJsonFOrdHed.put("InvAmt",
										InvAmt.replaceAll("[,]", ""));
								valuesJsonFOrdHed.put("OutDis",
										OutDis.replaceAll("[,]", ""));
								valuesJsonFOrdHed.put("InvDis",
										InvDis.replaceAll("[,]", ""));
								valuesJsonFOrdHed.put("TotMkrAmt",
										TotMkrAmt.replaceAll("[,]", ""));
								valuesJsonFOrdHed.put("UnOvAmt",
										UnOvAmt.replaceAll("[,]", ""));
								valuesJsonFOrdHed.put("TotalDis",
										TotalDis.replaceAll("[,]", ""));
								valuesJsonFOrdHed.put("TotalItmDis",
										LineItemsDisString.replaceAll("[,]", ""));
								valuesJsonFOrdHed.put("TotalAmt",
										TotalAmt.replaceAll("[,]", ""));
								valuesJsonFOrdHed.put("AddUser", AddUser);
								valuesJsonFOrdHed.put("AddMach", AddMach);
								valuesJsonFOrdHed.put("prtcopy", prtcopy);
								valuesJsonFOrdHed.put("InvFlg", InvFlg);
								valuesJsonFOrdHed.put("RecordId", RecordId);
								valuesJsonFOrdHed.put("TranBatch", TranBatch);
								valuesJsonFOrdHed.put("OutDisVal", outDisValue);
								valuesJsonFOrdHed.put("AddDate", UploadodAddDate);
								valuesJsonFOrdHed
										.put("DbName", currentUserServerDB);

								valuesarrayFordHed.put(valuesJsonFOrdHed
										.remove("[,]"));
								arFordHed.add(valuesJsonFOrdHed.toString());
							} catch (Exception Ex) {

							}

						}
						arrayLength = 7;
						progressHandler
								.sendMessage(progressHandler.obtainMessage());
					}
				}
				//checkNetworkUploading();
				if (selectOrderDetails != null) {
					if (selectOrderDetails.getCount() > 0) {
						while (selectOrderDetails.moveToNext()) {
							// FStOrderDetIndex = selectOrderDetails.getString(0);
							String Amt = selectOrderDetails.getString(1);
							String BAmt = selectOrderDetails.getString(2);
							String BDisAmt = selectOrderDetails.getString(3);
							String BSellPrice = selectOrderDetails.getString(4);
							String BTSellPrice = selectOrderDetails.getString(5);
							String BTaxAmt = selectOrderDetails.getString(6);
							String BalQty = selectOrderDetails.getString(7);
							String CaseQty = selectOrderDetails.getString(8);
							String CostPrice = selectOrderDetails.getString(9);
							String DisAmt = selectOrderDetails.getString(10);
							String DisPer = selectOrderDetails.getString(11);
							String Itemcode = selectOrderDetails.getString(12);
							String PiceQty = selectOrderDetails.getString(13);
							String Qty = selectOrderDetails.getString(14);
							String ReaCode = selectOrderDetails.getString(15);
							String RecordId = selectOrderDetails.getString(16);
							String RefNo = selectOrderDetails.getString(17);
							String SellPrice = selectOrderDetails.getString(18);
							String SeqNo = selectOrderDetails.getString(19);
							String TSellPrice = selectOrderDetails.getString(20);
							String TaxAmt = selectOrderDetails.getString(21);
							String TxnType = selectOrderDetails.getString(22);
							String Txnseqno = selectOrderDetails.getString(23);
							String Type = selectOrderDetails.getString(24);
							String TxnDate = selectOrderDetails.getString(25);
							String itemdisper = selectOrderDetails.getString(27);
							String itemdisperval = selectOrderDetails.getString(28);

							double totlineItemDis = Double.parseDouble(BDisAmt
									.replaceAll("[,]", ""));
							double DisPerAmount = Double.parseDouble(itemdisperval
									.replaceAll("[,]", ""));
							double DisValueAmtCal = totlineItemDis - DisPerAmount;
							String DisValueAmtCalStr = Double
									.toString(DisValueAmtCal);
							try {
								date = originalFormat.parse(TxnDate.replaceAll(
										"[-+/.^:,]", " "));
								TxnDate = targetFormat.format(date);
							} catch (ParseException ex) {
								TxnDate = "1900-01-01";
							}

							// Create values JSONArray
							JSONArray valuesarrayFordDet = new JSONArray();
							try {
								// Create values jsonObject
								JSONObject valuesJsonFOrdDet = new JSONObject();
								valuesJsonFOrdDet.put("RefNo", RefNo);
								valuesJsonFOrdDet.put("TxnDate", TxnDate);
								valuesJsonFOrdDet.put("TxnType", TxnType);
								valuesJsonFOrdDet.put("SeqNo", SeqNo);
								valuesJsonFOrdDet.put("Itemcode", Itemcode);
								valuesJsonFOrdDet.put("Txnseqno", Txnseqno);
								valuesJsonFOrdDet.put("SellPrice",
										SellPrice.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("BSellPrice",
										BSellPrice.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("TSellPrice",
										TSellPrice.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("BTSellPrice",
										BTSellPrice.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("CostPrice",
										CostPrice.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("CaseQty", CaseQty);
								valuesJsonFOrdDet.put("Type", Type);
								valuesJsonFOrdDet.put("PiceQty",
										PiceQty.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("Qty", Qty);
								valuesJsonFOrdDet.put("BalQty",
										BalQty.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("DisPer", DisPer);
								valuesJsonFOrdDet.put("DisAmt",
										DisAmt.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("BDisAmt", BDisAmt);
								valuesJsonFOrdDet.put("TaxAmt",
										TaxAmt.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("BTaxAmt",
										BTaxAmt.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("Amt", Amt);
								valuesJsonFOrdDet.put("BAmt",
										BAmt.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("ReaCode", ReaCode);
								valuesJsonFOrdDet.put("DisPerAmt",
										itemdisperval.replaceAll("[,]", ""));
								valuesJsonFOrdDet.put("DisValAmt",
										DisValueAmtCalStr.replaceAll("[,]", ""));
								valuesJsonFOrdDet
										.put("DbName", currentUserServerDB);

								valuesarrayFordDet.put(valuesJsonFOrdDet
										.remove("[,]"));
								arFordDet.add(valuesJsonFOrdDet.toString());
							} catch (Exception ex) {

							}
						}
						arrayLength = 7;
						progressHandler
								.sendMessage(progressHandler.obtainMessage());
					}
				}
				//checkNetworkUploading();
				String strFORDH = arFordHed.toString();
				String strFORDD = arFordDet.toString();

				if (selectOrderHeader.getCount() <= 0) {
					Log.v(TAG, "ARRAY 2" + strFORDH + "/" + strFORDD);
				} else {
					strFORDH = strFORDH.replace("[", "");
					strFORDH = strFORDH.replace("]", "");
					strFORDD = strFORDD.replace("[", "");
					strFORDD = strFORDD.replace("]", "");
					// PDADBWebServiceM
					HttpPost requestSOrd = new HttpPost(
							connectionURL
									+ "/PDADBWebServiceM/PDADBWebServiceRest.svc/updateFOrdHed");
					JSONStringer userJsonSOrd = null;
					try {
						userJsonSOrd = new JSONStringer().object().key("fOHed")
								.value(strFORDH).key("fODet").value(strFORDD);
					} catch (Exception e) {
					}

					StringEntity entityFSO = null;
					try {
						// String repval = userJson.toString() + "}" + ",UTF-8";
						String formatso1 = userJsonSOrd.toString().replace("[", "");
						String formatso2 = formatso1.replace("]", "");
						String formatso3 = formatso2.replace("\\", "");

						String formatso4 = "\"fOHed\":\"";
						// String ggg = ",\"fDet\":\"";
						String formatso5 = "\",\"fODet\":\"";

						String formatso6 = formatso3.replace(formatso4,
								"\"fOHed\":[");
						String formatso7 = formatso6.replace(formatso5,
								"],\"fODet\":[");
						formatso7 = formatso7 + "}";
						String sendReqSO = formatso7.replace("\"}\"}", "\"}]}");

						// Log.v(TAG, "JSON1 =" + ddddd);
						Log.v(TAG, "****************************************\n");
						Log.v(TAG, "JSON1 =" + sendReqSO);
						entityFSO = new StringEntity(sendReqSO, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					entityFSO.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
							"application/json"));
					entityFSO.setContentType("application/json");
					requestSOrd.setEntity(entityFSO);

					// Send request to WCF service
					DefaultHttpClient httpClientSO = new DefaultHttpClient();

					try {
						Log.e("response", "connect");
						HttpResponse responseSO = httpClientSO.execute(requestSOrd);
						// Log.e("RES DJ1:", "RES DJ1:" + responseSO.toString());
						// ===========================================================
						HttpEntity entitySO = responseSO.getEntity();
						is = entitySO.getContent();
						if (is != null) {

							try {
								BufferedReader reader_so = new BufferedReader(
										new InputStreamReader(is, "iso-8859-1"), 8);
								sb = new StringBuilder();
								sb.append(reader_so.readLine() + "\n");
								String line = "0";
								while ((line = reader_so.readLine()) != null) {
									sb.append(line + "\n");
								}
								is.close();
								String result_so = sb.toString();
								String result_so1 = result_so.replace("\"", "");
								if (result_so1.trim().equals("200")) {
									ContentValues fordhedSynUpdateVal = new ContentValues();
									fordhedSynUpdateVal.put("stordhedSync", "1");
									mydb.update(STOCK_ORDER_HEAD,
											fordhedSynUpdateVal,
											"stordhedSync ='0'", null);

									ContentValues forddetSynUpdateVal = new ContentValues();
									forddetSynUpdateVal.put("storddetSync", "1");
									mydb.update(STOCK_ORDER_DETAIL,
											forddetSynUpdateVal,
											"storddetSync ='0'", null);

									String fInvOrdCountStr = Integer
											.toString(fInvHedCount);
									SOupSummary = "(SO -" + fInvOrdCountStr + "/"
											+ fInvOrdCountStr + ")";
								}

								else {
									String result12 = result_so.replace("\",", "");
									String result13 = result12.replace("\"", "");
									String result14 = result13.replace("\\", "");
									String result15 = result14.replace("200,", "");
									String[] items = result15.split(",");
									List<String> container = Arrays.asList(items);
									List<String> android = new ArrayList<String>(
											container);
									Log.e("RES DJ2:", "RESULT ELSE 200 :" + android);
									// Getting Iterator from List
									Iterator<String> iteratorSO = android
											.iterator();
									Cursor selectStOrdHeadDetailsReChk = null, selectStOrdDetailsDataReChk = null;
									try {
										selectStOrdHeadDetailsReChk = mydb.query(
												STOCK_ORDER_HEAD, null,
												"stordhedSync ='0'", null, null,
												null, null);
									} catch (Exception e) {
									}
									try {
										selectStOrdDetailsDataReChk = mydb.query(
												STOCK_ORDER_DETAIL, null,
												"storddetSync ='0'", null, null,
												null, null);
									} catch (Exception e) {
									}
									while (iteratorSO.hasNext()) {
										String ReadRefNumbers = iteratorSO.next();
										Log.e("RES DJ2:", "UploadError REF:"
												+ ReadRefNumbers);
										if (selectStOrdHeadDetailsReChk != null) {
											if (selectStOrdHeadDetailsReChk
													.getCount() > 0) {
												while (selectStOrdHeadDetailsReChk
														.moveToNext()) {
													String mainRefNoErrorHed = selectStOrdHeadDetailsReChk
															.getString(16);
													ContentValues fStOrdhedSynUpdaterall = new ContentValues();
													fStOrdhedSynUpdaterall.put(
															"stordhedSync", "7");
													mydb.update(
															STOCK_ORDER_HEAD,
															fStOrdhedSynUpdaterall,
															"RefNo ='"
																	+ mainRefNoErrorHed
																	+ "'", null);
												}
											}
										}

										if (selectStOrdDetailsDataReChk != null) {
											if (selectStOrdDetailsDataReChk
													.getCount() > 0) {
												while (selectStOrdDetailsDataReChk
														.moveToNext()) {
													String mainRefNoErrorDet = selectStOrdDetailsDataReChk
															.getString(17);
													ContentValues fStOrddetSynUpdaterall = new ContentValues();
													fStOrddetSynUpdaterall.put(
															"storddetSync", "7");
													mydb.update(
															STOCK_ORDER_DETAIL,
															fStOrddetSynUpdaterall,
															"RefNo ='"
																	+ mainRefNoErrorDet
																	+ "'", null);
												}
											}
										}

										fOrdHedCountFail = fOrdHedCountFail + 1;
										String fInvOrdCountStr = Integer
												.toString(fOrdHedCount);
										String fInvOrdCountStrFail = Integer
												.toString(fInvHedCountFail);
										SOupSummary = "(SO -" + fInvOrdCountStrFail
												+ "/" + fInvOrdCountStr + ")";
										iteratorSO.remove();
									}

									Cursor selectStOrdHeadDetailsUpdate = null, selectStOrdDetailsDataUpdate = null;
									try {
										selectStOrdHeadDetailsUpdate = mydb.query(
												STOCK_ORDER_HEAD, null,
												"stordhedSync ='0'", null, null,
												null, null);
									} catch (Exception e) {
									}
									try {
										selectStOrdDetailsDataUpdate = mydb.query(
												STOCK_ORDER_DETAIL, null,
												"storddetSync ='0'", null, null,
												null, null);
									} catch (Exception e) {
									}

									if (selectStOrdHeadDetailsUpdate != null) {
										if (selectStOrdHeadDetailsUpdate.getCount() > 0) {
											while (selectStOrdHeadDetailsUpdate
													.moveToNext()) {
												String mainRefNoHed = selectStOrdHeadDetailsUpdate
														.getString(16);
												ContentValues fStOrdhedSynUpdaterall = new ContentValues();
												fStOrdhedSynUpdaterall.put(
														"stordhedSync", "1");
												mydb.update(STOCK_ORDER_HEAD,
														fStOrdhedSynUpdaterall,
														"RefNo ='" + mainRefNoHed
																+ "'", null);
											}
										}
									}
									if (selectStOrdDetailsDataUpdate != null) {
										if (selectStOrdDetailsDataUpdate.getCount() > 0) {
											while (selectStOrdDetailsDataUpdate
													.moveToNext()) {
												String mainRefNoDet = selectStOrdDetailsDataUpdate
														.getString(17);
												ContentValues fStOrddetSynUpdaterall = new ContentValues();
												fStOrddetSynUpdaterall.put(
														"storddetSync", "1");
												mydb.update(STOCK_ORDER_DETAIL,
														fStOrddetSynUpdaterall,
														"RefNo ='" + mainRefNoDet
																+ "'", null);
											}
										}
									}

									Cursor selectStOrdHeadDetailsChkFail = null, selectStOrdDetailsDataChkFail = null;
									try {
										selectStOrdHeadDetailsChkFail = mydb.query(
												STOCK_ORDER_HEAD, null,
												"stordhedSync ='7'", null, null,
												null, null);
									} catch (Exception e) {
									}
									try {
										selectStOrdDetailsDataChkFail = mydb.query(
												STOCK_ORDER_DETAIL, null,
												"storddetSync ='7'", null, null,
												null, null);
									} catch (Exception e) {
									}

									if (selectStOrdHeadDetailsChkFail != null) {
										if (selectStOrdHeadDetailsChkFail
												.getCount() > 0) {
											while (selectStOrdHeadDetailsChkFail
													.moveToNext()) {
												String mainRefNoHedFail = selectStOrdHeadDetailsChkFail
														.getString(16);
												ContentValues fStOrdhedSynUpdaterallFail = new ContentValues();
												fStOrdhedSynUpdaterallFail.put(
														"stordhedSync", "0");
												mydb.update(STOCK_ORDER_HEAD,
														fStOrdhedSynUpdaterallFail,
														"RefNo ='"
																+ mainRefNoHedFail
																+ "'", null);
											}
										}
									}
									if (selectStOrdDetailsDataChkFail != null) {
										if (selectStOrdDetailsDataChkFail
												.getCount() > 0) {
											while (selectStOrdDetailsDataChkFail
													.moveToNext()) {
												String mainRefNoDetFail = selectStOrdDetailsDataChkFail
														.getString(17);
												ContentValues fStOrddetSynUpdaterallFail = new ContentValues();
												fStOrddetSynUpdaterallFail.put(
														"storddetSync", "0");
												mydb.update(STOCK_ORDER_DETAIL,
														fStOrddetSynUpdaterallFail,
														"RefNo ='"
																+ mainRefNoDetFail
																+ "'", null);
											}
										}
									}

								}

							} catch (Exception e1) {
								e1.printStackTrace();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					arFordHed.clear();
					arFordDet.clear();
				}
			
				return null;
			}

			@Override
			protected void onPostExecute(Void args) {
				mProgressDialog.dismiss();
				SynchDetails.dismiss();

				String AlertMessageUploading = SIupSummary + " / " + SOupSummary
						+ "Uploading Data Completed..";
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_Application_Manage_Tools.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("UPLOAD STATUS");
				// Setting Dialog Message
				alertDialog.setMessage(AlertMessageUploading);
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						fInvHedCount = 0;
						fOrdHedCount = 0;
						fInvHedCountFail = 0;
						fOrdHedCountFail = 0;
						alertDialog.dismiss();
					}
				});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				return;

			}
		}

		// handler for the background updating
		Handler progressHandler = new Handler() {
			public void handleMessage(Message msg) {
				mProgressDialog.incrementProgressBy(arrayLength);
			}
		};
}
